The Definitive Guide to Google Maps Markers

Here is the list of most common topics that everybody who’s working with markers in Google Maps is facing from time to time. The list contains simple topics like adding/removing markers, but that’s for the sake of having all subjects in one place. In each section there is a code snippets with optional link to live preview.

Contents

How to add marker

Adding new Marker is easy, all you need to do is to call Marker constructor with additional options, and the mandatory parameter is a map, where you want to put a marker.

function add_marker(gmap, coordinates, text) {
   var marker = new google.maps.Marker({
        position: coordinates,
        map: gmap,
        label: { text: text }
    });

   return marker;
}

Live preview or view source code

How to remove marker

There are two ways to remove marker from a map. The first one is to hide it using Maker.setVisible method and the second is to set the value of map where you want to put the marker to null using Marker.setMap method. The difference between two methods is that the setVisible just hide marker and preserves resources and the setMap removes marker and releases allocated resources.

If you want to show/hide small number of markers you can use setVisible methodbut imagine you have 10.000 of markers and you want periodically hide them. In this case using setVisible method maybe not such a good idea, as all hidden markers hanging on the map and use resources, so in this case using setMap method maybe a better choice.

function add_marker(gmap, coordinates, text) {
    var marker = new google.maps.Marker({
        position: coordinates,
        map: gmap,
        label: { text: text }
    });

    return marker;
}

var gmap = new google.maps.Map(document.getElementById('map'),
    {
        zoom: 4,
        center: { lat: 50.43333333, lng: 30.516667 }
    });

var marker = add_marker(gmap, { lat: 50.43333333, lng: 30.516667 }, 'UA');
// just hide it
marker.setVisible(false);
// or completely remove from a map
marker.setMap(null);

How to auto center map on markers

Suppose you have a bunch of stores in different countries scattered by cities. What you want is to guide user through all of them and auto-center map on interested country. There are at least two method:

  • Calculate centroid on list of points in specific country.
  • Use LatLngBounds class to extend the bounds of rectangle from list of points and then compute the center using getCenter method.

Live preview or view source code

auto_center
Moving through list of places

How to add custom data to marker

Just set the properties of Marker class to some predefined data. Let’s look into example: When someone click on marker – alert custom data info:

<script>
function add_marker(gmap, coordinates, text) {
  var marker = new google.maps.Marker({
    position: coordinates,
    map: gmap,
    label: { text: text }
  });

  return marker;
}

function init_map() {
  var places = {
    'UA': { lat: 50.43333333, lng: 30.516667 },
    'DE': { lat: 52.51666667, lng: 13.4 },
    'GL': { lat: 64.18333333, lng: -51.75 },
    'JP': { lat: 35.68333333, lng: 139.75 },
    'MG': { lat: -18.91666667, lng: 47.516667 }
  };

  var gmap = new google.maps.Map(document.getElementById('map'),
    {
      zoom: 2,
      center: { lat: -25.363, lng: 131.044 }
    });

  for (var country in places) {
    var marker = add_marker(gmap, places[country], country);
    marker.countryInfo = country;
    google.maps.event.addListener(marker, 'click', function () {
      alert('Clicked on ' + this.countryInfo + ' country');
    });
  }
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?callback=init_map"></script>

How to get coordinates when moving marker

If you want to track position of marker when user is moving it, you need to listen on the following events:

  • dragstart: user started dragging marker.
  • drag: in process of dragging.
  • dragend: finished.

Here is the excerpt from source code to listen on the above events:

var marker = add_marker(gmap, places[country], country);
marker.countryInfo = country;
google.maps.event.addListener(marker, 'dragstart', function (event) {
    console.log(this.countryInfo + ': Start position: ', coords2text(this.getPosition()));
});
google.maps.event.addListener(marker, 'drag', function (event) {
    console.log(this.countryInfo + ': Current position: ', coords2text(this.getPosition()));
});
google.maps.event.addListener(marker, 'dragend', function (event) {
    console.log(this.countryInfo + ': Finished at: ', coords2text(this.getPosition()));
});

Live preview or view source code

How to adjust zoom level to include all visible markers on screen

There is no need to calculate distance between markers, trying to get scale ratio for zoom levels, etc., because there exists function fitBounds, which doing all the mentioned steps under the hood. So, in order to automatically adjust zoom level according to number of marker on the map, all is needed is to extend LatLngBounds to included all markers position and then call fitBounds function.

Live preview or view source code

How to resize marker image

When using custom icon in marker the default size of icon is the original size of image. In order to scale image to particular size the scaledSize property must be used.

function add_marker(gmap, coordinates, icon) {
    var marker = new google.maps.Marker({
        position: coordinates,
        map: gmap,
        icon: icon
    });

    return marker;
}

function init_map() {
    var places = {
        'UA': { lat: 50.43333333, lng: 30.516667 },
        'DE': { lat: 52.51666667, lng: 13.4 },
        'GL': { lat: 64.18333333, lng: -51.75 },
        'JP': { lat: 35.68333333, lng: 139.75 },
        'MG': { lat: -18.91666667, lng: 47.516667 }
    };

    var gmap = new google.maps.Map(document.getElementById('map'),
        {
            zoom: 2,
            center: { lat: -25.363, lng: 131.044 }
        });

    var size = 25;
    for (var country in places) {
        var icon = {
            url: "images/pin.png",
            scaledSize: new google.maps.Size(size, size),
        };
        add_marker(gmap, places[country], icon);
        size += 10;
    }
}

Live preview or view source code

How to add info window to marker

Google maps contains built-in class for showing info window over some map element, named InfoWindow. Using and styling info windows is pretty easy:

  • Content property – string with HTML elements that would be located in rectangular area in predefined position.
  • Open method which receive map and anchor as input in order to show info window.

Live preview or view source code

How to add marker using URL format

When you want to put marker on a Google map without writing code at all, you can use the following URL format:

http://maps.google.com/maps?&z=ZOOM_LEVEL&q=LATITUDE+LONGITUDE

Try this one: http://maps.google.com/maps?&z=9&q=35.68333333+139.75

How to use Font Awesome as marker icon

Fontawesome is a set of vector icons that be easily customized using CSS.  It contains nearly 675 icons divided by categories which makes it perfect candidate for custom marker icon.

In order to use Fontawesome as custom marker icon we need to switch from Marker class to RichMarker class. The latter designed for defining marker as arbitrary DOM element. Now, after switching to RichMarker library it’s very easy to define custom icon: just copy name of icon from Fontawesome website to the RichMarker content property.

function add_marker(gmap, coordinates, content) {
    var marker = new RichMarker({
        position: new google.maps.LatLng(coordinates),
        map: gmap,
        flat: true,
        anchor: RichMarkerPosition.MIDDLE,
        content: content
    });

    return marker;
}
// adding gear spinning animation as marker icon
add_marker(gmap, { lat: 48.857487, lng: 33.222656 },
   '<i class="fa fa-gear fa-spin fa-fw fa-2x" style="color:green"></i>');

Live preview or view source code

How to use SVG as marker icon

Marker class has a possibility to define custom marker icon as SVG path data, which is very powerful concept as you can mix vector/raster graphics in XML. There are predefined set of built-in symbol paths which can be customized using icon properties like: scale, strokeWeight, strokeColor, fillColor, etc.

In the linked demo, you can find basic usage of SVG icon. We are using predefined CIRCLE path and customized color, scale, fillColor, etc in order to show population by country. The larger population the bigger scale and color depth.

Live preview or view source code

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s