DEV Community

loading...
Cover image for An Introduction to Google Maps in JavaScript

An Introduction to Google Maps in JavaScript

Peter Klingelhofer
Software Engineer
Updated on ・3 min read

Introduction

Google Maps is a powerful tool you can easily add to your JavaScript skillset. Here, we will display Markers on a Google Map centered over New Orleans. Then, we will ask the user for their location, and if the user provides it, re-centers the map over their location. Finally, we will display multiple markers near each other as a cluster. When clicked, the map zooms into the area where those three markers are located.

Creating Markers on a Google Map

Thankfully, Google has made displaying a Marker in Google Maps quite simple. In a map initialization function, declare an object with the coordinates of the Marker you desire.

Create a new constant called map, instantiate a new Google Maps map with a specified zoom parameter (an integer between 5 and 15), and a center key supplied with the coordinates object you created above.

Then create a third constant called marker with a position key again supplied with the coordinates object you created above, a map key with the map created above, (map: map can be shortened to map now with ES6 syntax), and a title key with a string with a Marker title of your choosing.

function initMap() {
  const coordinates = {lat: 30.0326996, lng: -90.1627533};

  const map = new google.maps.Map(document.getElementById('map'), {
    zoom: 8,
    center: coordinates
  });

  const marker = new google.maps.Marker({
    position: coordinates,
    map,
    title: 'Welcome to New Orleans!'
  });
}
Enter fullscreen mode Exit fullscreen mode

Alt Text

You can read more about Markers in Google Maps here.

Geolocation

Asking for a user's location is quite simple as well. Here we use the navigator.geolocation.getCurrentPosition function and destructure out latitude and longtiude from position.coords. We then set the userLocation state of the React Functional Component, so that the map will move to the userLocation.

   navigator.geolocation.getCurrentPosition((position) => {
      const { latitude, longitude } = position.coords;
      setUserLocation({ lat: latitude, lng: longitude });
    });
Enter fullscreen mode Exit fullscreen mode

Marker Clustering

Sometimes, when there are a lot of Markers in a single area and the user is zoomed out, Markers can start to get pretty cluttered depending on the data type you're representing.

First, after initializing the map with new google.maps.Map, set the zoom and center as we did above. Create a constant for the labels, and a constant for the markers. Map the locations, returning new google.maps.Marker which takes an object as a parameter with key position, supply it location, and a key label, supply it labels[i % labels.length].

Then, create a constant called markerCluster and initialize the Marker Clusterer with new MarkerClusterer with parameters map, marker, and an object with the imagePath. Below that, declare

      const locations = [
        {lat: 30.0326996, lng: -90.1627533},
        {lat: 30.0426996, lng: -90.2627533},
        {lat: 30.0526996, lng: -90.3627533},
      ]

      function initMap() {
        const map = new google.maps.Map(document.getElementById('map'), {
          zoom: 8,
          center: {lat: 30.0326996, lng: -90.1627533}
        });

        const labels = '123456789';

        const markers = locations.map(function(location, i) {
          return new google.maps.Marker({
            position: location,
            label: labels[i % labels.length]
          });
        });

        const markerCluster = new MarkerClusterer(map, markers,
            {imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'});
      }
Enter fullscreen mode Exit fullscreen mode

Read more here about Marker Clustering here.

Alt Text

Conclusion

For more reading, the documentation for Google Maps in JavaScript is quite comprehensive. We went through creating Markers, using Geolocation, and performing Marker Clustering. Google Maps can be a robust asset to incorporate into your project.

Discussion (0)

Forem Open with the Forem app