Skip to content

Instantly share code, notes, and snippets.

@nncl
Last active September 3, 2015 14:35
Show Gist options
  • Save nncl/c2ec8b8bbbe7eaeb3c67 to your computer and use it in GitHub Desktop.
Save nncl/c2ec8b8bbbe7eaeb3c67 to your computer and use it in GitHub Desktop.
Multiple Markers w/ Google Maps API

Google Maps API

Multiple Markers

This is an example of how we can build with Google API a map that contains more than one simple marker.

Check the result [here] (http://codepen.io/nncl/pen/QjwKYL).

The HTML

Instead of the HTML tag, we need to call the Google Maps API.

<script src="https://maps.googleapis.com/maps/api/js?callback=callMap" async defer></script>

If the function callMap is not on the DOM, just remove the callback and async defer:

<script src="https://maps.googleapis.com/maps/api/js"></script>

Now, the HTML tag:

<div id="map"></div>

Now, everybody:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Google Maps JS - Multiple Markers</title>
  </head>
  <body>
    <div id="map"></div>
    
    <script src="https://maps.googleapis.com/maps/api/js"></script>
    <script src="/js/map.min.js"></script>
  </body>
</html>

The JSON Structure

Here, we need/can to tell the title of marker - it showed on click - and the latitude and longitude positions.

{
  "points" : [
    [
      "Chronic Rua Maria Joaquina", 
      -23.534749, 
      -46.611924
    ],
    [
      "Chronic Rua da Juta", 
      -23.539512,
      -46.619652
    ]
  ]
}

The Javascript

$public.map = function() {

  $.get('https://gist.githubusercontent.com/mariosmello/d6cce41514d6fa2e8ef6/raw/c6eecd00ed62302ebda36d488334f3ee265b291c/beaches-google.json', function(data) {

    var bounds = new google.maps.LatLngBounds();
  
    var mapOptions = {
      zoom: 15,
      zoomControl: true,
      scrollwheel: false
    };
  
    var map = new google.maps.Map(document.getElementById('map'), mapOptions);
    
    var infowindow = new google.maps.InfoWindow();
    var marker;
  
    $(data.points).each(function( i, o ) {
    
      marker = new google.maps.Marker({
        position: new google.maps.LatLng(o[1], o[2]),
        map: map
      });
    
      bounds.extend(marker.position);
    
      google.maps.event.addListener(marker, 'click', (function(marker, i) {
        return function() {
          infowindow.setContent(o[0]);
          infowindow.open(map, marker);
        }
      })(marker, i));
    
    });
  
    map.fitBounds(bounds);
    var listener = google.maps.event.addListener(window, 'load', function() {
      map.setZoom(3);
      google.maps.event.removeListener(listener);
    });

  }, 'json');

}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment