Skip to content

Instantly share code, notes, and snippets.

@gagimilicevic
Last active November 15, 2019 12:02
Show Gist options
  • Save gagimilicevic/92998cf1c6afe9ce5c6ebd6d47f532ba to your computer and use it in GitHub Desktop.
Save gagimilicevic/92998cf1c6afe9ce5c6ebd6d47f532ba to your computer and use it in GitHub Desktop.
Auto-center map with multiple markers in Google Maps API v3
var markers = [];
var markersListeners = [];
var LatLngList=[];
var infowindow = new google.maps.InfoWindow();
var marker, i;
var locations = $.parseJSON(data);
var bounds = new google.maps.LatLngBounds();
var initial_coordinates = {lat: locations[0]['lat'], lng: locations[0]['lng']};
var map = new google.maps.Map(document.getElementById('small_map_directions'), {
//zoom: 4,
//center: new google.maps.LatLng(locations[0]['lat'], locations[0]['lng']),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var j=0;
for (i = 0; i < locations.length; i++) {
j=j+1;
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i]['lat'], locations[i]['lng']),
map: map,
title: locations[i]['title']+ '-' +locations[i]['faa_id']
});
markers.push(marker);
var content = '<div id="content">'+
'<div id="siteNotice">'+
'</div>'+
'<h4 id="firstHeading" class="firstHeading">'+ locations[i]['title'] +'</h4>'+
'<div id="bodyContent">'+
'<p><b>FAA ID: </b>'+ locations[i]['faa_id'] +'</p>'+
'<p><b>City: </b>'+ locations[i]['city'] + ' <b>State: </b>'+ locations[i]['state'] + ' <b>Country: </b>'+ locations[i]['country'] +'</p>'+
'<p><b>Latitude: </b>'+ locations[i]['lat'] + ' | <b>Longitude: </b>'+ locations[i]['lng'] + '</p>' +
'<p><a href="' + locations[i]['airport_link'] + '"><b>Read more about this airport</b></a>'+ '</p>' +
'</div>'+
'</div>';
var infowindow = new google.maps.InfoWindow();
google.maps.event.addListener(marker,'click', (function(marker,content,infowindow){
return function() {
infowindow.setContent(content);
infowindow.open(map,marker);
};
})(marker,content,infowindow));
if (i===locations.length-1){
j=j-1;
}
var randomColor = '#' + Math.floor(Math.random() * 16777215).toString(16);
var line = new google.maps.Polyline({
path: [
new google.maps.LatLng(locations[i]['lat'], locations[i]['lng']),
new google.maps.LatLng(locations[j]['lat'], locations[j]['lng'])
],
strokeColor: randomColor,
strokeOpacity: 1.0,
strokeWeight: 3,
map: map
});
bounds.extend(marker.position);
}
console.log(bounds);
map.fitBounds(bounds);
//(optional) restore the zoom level after the map is done scaling
var listener = google.maps.event.addListener(map, "idle", function () {
map.setZoom(3);
google.maps.event.removeListener(listener);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment