[For beginners] How to display maps and search boxes using the GoogleMap Javascript API

How to add a map on your app using the googlemap API.

Basically, it can be realized by writing [Official document] 1 ~~ along copy and paste ~~, but I am a Javascript beginner and it took a long time to decipher, so I will start the same thing I'll share it for you.

What you can do

・ Map display ・ Display of search box ・ Map and search box decoration ezgif.com-gif-maker.gif

With a little modification, It can also be decorated. ezgif.com-gif-maker (1).gif

procedure

  1. Describe the id in the html file where you want to place the map
  2. Describe the Web API in the javascript file
  3. Play with CSS to decorate the map

only this.

Step 1: Write the id in the html file where you want to place the map

The following is a quote from [Official Document] 1. The point is to describe libraries = places in the API call script. This allows you to load the library that switches the screen to the search & search position.

sample.html


<!DOCTYPE html>
<html>
  <head>
    <title>Places Search Box</title>
    <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
    #"Key=YOUR_Describe the acquired API key in the "API" part
    #Since we will add a search function this time, we will use the Places library, so "libraries"=places ”added
    #"V="Weekly" indicates the update frequency of the map itself. If nothing is described, it will be updated once a quarter, and with this description, it will be updated weekly to keep it up to date, so you do not need to describe it separately.
    <script
      src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initAutocomplete&libraries=places&v=weekly"
      defer
    ></script>
    <link rel="stylesheet" type="text/css" href="./style.css" />
    <script src="./index.js"></script>
  </head>
  <body>
  #Display the map with javascript at the id specified here.
    <input
      id="pac-input"
      class="controls"
      type="text"
      placeholder="Search Box"
    />
    <div id="map"></div>
  </body>
</html>

If you open the browser in this state, you will find only a search box. Let's go to the next.

Step 2: Write the Web API in the javascript file

The following is also a quote from [Official Document] 1, but it took time to find out where the description came from one by one. ..

For beginners, I would like to briefly explain the description of js. const ~~ defines a constant "~~" there. function ~~ is a function. google.maps is an object that specifies the map itself.

index.js


function initAutocomplete() {
  //This is the default setting of the map.
  const map = new google.maps.Map(document.getElementById("map"), {
    center: { lat: -33.8688, lng: 151.2195 },
    zoom: 13,
    mapTypeId: "roadmap",
  });
  const input = document.getElementById("pac-input");
  const searchBox = new google.maps.places.SearchBox(input);
 ////"SearchBox class"Is a method of the Places library. Argument is input(There is an inputField on the document)。
 ////[https://developers.google.com/maps/documentation/javascript/reference/places-widget#SearchBox]
  
  map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
  ////"ControlPosition"The class positions the controller.
  ////https://lab.syncer.jp/Web/API/Google_Maps/JavaScript/ControlPosition/
  ////https://developers.google.com/maps/documentation/javascript/examples/control-positioning
  
  map.addListener("bounds_changed", () => {
    searchBox.setBounds(map.getBounds());
  });
  ////"bound_changed"The event is(Fired when there is a change in the map / viewport of the visible range)
  ////https://lab.syncer.jp/Web/API/Google_Maps/JavaScript/Map/bounds_changed/ 
  ////"getBounds"The method gets the viewport boundaries. Map class method.
  ////https://lab.syncer.jp/Web/API/Google_Maps/JavaScript/Map/getBounds/
  
  let markers = [];
  searchBox.addListener("places_changed", () => {
  ////"place_chaged"The event is an event of the AutoComplete class.
  ////https://developers.google.com/maps/documentation/javascript/reference/places-widget#Autocomplete.place_changed
  
    const places = searchBox.getPlaces();
    ////"getPlaces"Method is query(Search keyword)Array(PlaceResult)Return with.
    ////https://developers.google.com/maps/documentation/javascript/reference/places-widget#Autocomplete.place_changed

    if (places.length == 0) {
      return;
    }
    // Clear out the old markers.
    markers.forEach((marker) => {
      //"forEach"The method is the key of the Map object to the function in the argument/Assign values in order and execute the function.
        //Map object:
          //https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/Map
      marker.setMap(null);
      ////The setMap method is Marker(Polyline,Circle etc.)Method of class. Place the Marker in the specified position. If the argument is null, it will be removed from the map.
    });
    markers = [];
    // For each place, get the icon, name and location.
    const bounds = new google.maps.LatLngBounds();
    ////"LatLngBounds"The class creates an instrument that creates boundaries. The arguments are the lower left and upper right coordinates.
    ////https://lab.syncer.jp/Web/API/Google_Maps/JavaScript/LatLngBounds/#:~:text=LatLngBounds%E3%82%AF%E3%83%A9%E3%82%B9%E3%81%AF%E5%A2%83%E7%95%8C(Bounding,%E4%BD%9C%E3%82%8B%E3%81%93%E3%81%A8%E3%82%82%E3%81%A7%E3%81%8D%E3%81%BE%E3%81%99%E3%80%82
    places.forEach((place) => {
      if (!place.geometry) {
        ////"geometry"Is a method of the place library.
        
        console.log("Returned place contains no geometry");
        return;
      }
      const icon = {
        url: place.icon,
        ////"icon"Is an object that represents an icon. When you want to make the marker an original image.
        ////https://lab.syncer.jp/Web/API/Google_Maps/JavaScript/Icon/
        size: new google.maps.Size(71, 71),
        origin: new google.maps.Point(0, 0),
        anchor: new google.maps.Point(17, 34),
        ////"Point"A class is an instance method that determines the position of a marker label or the like.
        ////https://lab.syncer.jp/Web/API/Google_Maps/JavaScript/Point/
        
        scaledSize: new google.maps.Size(25, 25),
      };
      // Create a marker for each place.
      markers.push(
        new google.maps.Marker({
          map,
          icon,
          title: place.name,
          position: place.geometry.location,
        })
      );

      if (place.geometry.viewport) {
        ////viewport"Method
        // Only geocodes have viewport.
        bounds.union(place.geometry.viewport);
        ////"union"The method is a method of the LatLngBounds class. Incorporates the specified boundary into its own boundary and synthesizes it.
        ////https://lab.syncer.jp/Web/API/Google_Maps/JavaScript/LatLngBounds/union/
      } else {
        bounds.extend(place.geometry.location);
        ////"extend"The method is a method of the LatLngBounds class. Add new position coordinates to your boundaries.
        ////https://lab.syncer.jp/Web/API/Google_Maps/JavaScript/LatLngBounds/extend/
      }
    });
    map.fitBounds(bounds);
    ////"fitBounds"The method is a method of the map class. Change the viewport to a position where you can easily see the specified boundary.
    ////https://lab.syncer.jp/Web/API/Google_Maps/JavaScript/Map/fitBounds/#:~:text=Map.fitBounds()%E3%81%AFMap,%E5%A4%89%E6%9B%B4%E3%81%97%E3%81%A6%E3%81%8F%E3%82%8C%E3%81%BE%E3%81%99%E3%80%82

  });
}

style.css


#map {
  height: 100%;
}

html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}

#description {
  font-family: Roboto;
  font-size: 15px;
  font-weight: 300;
}

#infowindow-content .title {
  font-weight: bold;
}

#infowindow-content {
  display: none;
}

#map #infowindow-content {
  display: inline;
}

.pac-card {
  margin: 10px 10px 0 0;
  border-radius: 2px 0 0 2px;
  box-sizing: border-box;
  -moz-box-sizing: border-box;
  outline: none;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
  background-color: #fff;
  font-family: Roboto;
}

#pac-container {
  padding-bottom: 12px;
  margin-right: 12px;
}

.pac-controls {
  display: inline-block;
  padding: 5px 11px;
}

.pac-controls label {
  font-family: Roboto;
  font-size: 13px;
  font-weight: 300;
}

#pac-input {
  background-color: #fff;
  font-family: Roboto;
  font-size: 15px;
  font-weight: 300;
  margin-left: 12px;
  padding: 0 11px 0 13px;
  text-overflow: ellipsis;
  width: 400px;
}

#pac-input:focus {
  border-color: #4d90fe;
}

#title {
  color: #fff;
  background-color: #4d90fe;
  font-size: 25px;
  font-weight: 500;
  padding: 6px 12px;
}

#target {
  width: 345px;
}

You should now see the map and search box.

Feel free to play with css to your liking.

If you write a constant or function with the same name separately, it will not work well. Please check in case of an error.

Step 3: Play with CSS to decorate your map

If you leave step 2, the search box will be in an unsophisticated position, so decorate the box.

of js file

  map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);

The position of the search box has been placed in TOP_LEFT with.

Since javascript is loaded after reading css, It will be specified by overwriting the description of css.

Delete this line and decorate the id and class of the input tag with CSS as you like.

Play map style with snazzy

This site called [snazzy] [4] allows you to edit intuitively as you like. The style selected or edited here can copy JSON data, so you can edit the style as you like by pasting it into JS as it is.

Just playing with snazzy is fun, so please take a look. [4]:https://snazzymaps.com/editor/customize/21

By the way, the purple map style pasted at the beginning of the article is as follows.

input.js


const map = new google.maps.Map(document.getElementById("map"), opts);
var opts = {
    zoom: 15,
    center: { lat: -33.8688, lng: 151.2195 },
    styles: [
      //Hide all labels
      {
        featureType: 'all',
        elementType: 'labels',
        stylers: [
          {visibility: 'off'},
        ],
      },
      {
        featureType: 'transit',
        elementType: 'labels',
        stylers: [
          {visibility: 'on'},
        ],
      },
      //poi=Redisplay only the "Sightseeing spots, facilities, etc." icon
      {
        featureType: 'poi',
        elementType: 'labels.icon',
        stylers: [
          {visibility: 'inherit'},
        ],
      },
      //Customize the color of the entire map
      //Unify the basic color to red+Desaturate
      {
        featureType: 'all',
        elementType: 'all',
        stylers: [
          {hue: '#5f0285'},
          {saturation : -50},
        ],
      }
    ]

that's all. If it doesn't work, please follow the official documentation.

Recommended Posts

[For beginners] How to display maps and search boxes using the GoogleMap Javascript API
[Map display] Display a map from the address registered by the user using the Google Maps JavaScript API and Geocoding API!
[Rails] google maps api How to post and display including map information
How to display Map using Google Map API (Android)
For the time being using FastAPI, I want to display how to use API like that on swagger
Python # How to check type and type for super beginners
How to learn TensorFlow for liberal arts and Python beginners
[For beginners] I tried using the Tensorflow Object Detection API
How to execute the sed command many times using the for statement
How to use bing search api
How to display bytes in the same way in Java and Python
How to study for the Deep Learning Association G test (for beginners) [2020 version]
[Python] How to specify the window display position and size of matplotlib
How to divide and process a data frame using the groupby function
Search for Twitter keywords with tweepy and write the results to Excel
Trial to judge the timing of the progress display of the for loop using 0b1111 ~
How to search using python's astroquery and get fits images with skyview
How to display the progress bar (tqdm)
Implementation and explanation using XGBoost for beginners
[Rails] How to calculate latitude and longitude with high accuracy using Geocoding API and display it on Google Map
How to use Service Account OAuth and API with Google API Client for python
The fastest way for beginners to master Python
How to specify the launch browser for JupyterLab 3.0.0
I checked the library for using the Gracenote API
Causal reasoning and causal search with Python (for beginners)
[Python] How to change the date format (display format)
Display Google Maps API with Rails and pin display
How to use data analysis tools for beginners
How to use the Google Cloud Translation API
How to use the NHK program guide API
How to get article data using Qiita API
How to search HTML data using Beautiful Soup
How to make Python faster for beginners [numpy]
[For beginners] How to study programming Private memo
How to find the correlation for categorical variables
Tips for Python beginners to use the Scikit-image example for themselves 7 How to make a module
I tried to notify the update of "Become a novelist" using "IFTTT" and "Become a novelist API"
How to use the grep command to recursively search directories and files to a specified depth
[For beginners] Language analysis using the natural language processing tool "GiNZA" (from morphological analysis to vectorization)
I tried to score the syntax that was too humorous and humorous using the COTOHA API.
A story about a Python beginner trying to get Google search results using the API
How to confirm the Persival theorem using the Fourier transform (FFT) of matplotlib and scipy
How to find out which process is using the localhost port and stop it
[Rails] How to get location information using Geolocation API
[BigQuery] How to use BigQuery API for Python -Table creation-
How to write a GUI using the maya command
How to convert Python # type for Python super beginners: str
[For beginners] How to study Python3 data analysis exam
How to use the grep command and frequent samples
Send and receive Gmail via the Gmail API using Python
Post to your account using the API on Twitter
How to use argparse and the difference between optparse
How to analyze with Google Colaboratory using Kaggle API
[Introduction to Python] How to stop the loop using break?
Using the National Diet Library Search API in Python
How to post a ticket from the Shogun API
[Introduction to Python] How to write repetitive statements using for statements
[For those who want to use TPU] I tried using the Tensorflow Object Detection API 2
[Super easy! ] How to display the contents of dictionaries and lists including Japanese in Python
How to get the current weather data and display it on the GUI while updating it automatically
[Sakura Rental Server] (For beginners) How to build an environment for Python, pyenv, and Flask. | For csh