Created
January 31, 2012 10:59
-
-
Save sebnilsson/1709905 to your computer and use it in GitHub Desktop.
Init Google Maps via Javascript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Needs reference to 'http://maps.google.com/maps/api/js?sensor=false'. Optional: '&language=en'. | |
// mapElement should contain a 'data-locations'-attribute with JSON-formatted objects | |
// with properties 'lat', 'long', 'title' and optional 'description' | |
var initMap = function (mapElement) { | |
var dataLocations = $(mapElement).attr('data-locations'); // Find DOM-attribute containing locations | |
var markerPositions = ($.parseJSON(dataLocations) || { locations: [] }).locations || []; | |
var latlng = new google.maps.LatLng(59.33279, 18.06449); | |
options = { | |
zoom: 3, | |
center: latlng, | |
mapTypeId: google.maps.MapTypeId.ROADMAP, | |
mapTypeControl: false | |
}; | |
var map = new google.maps.Map(mapElement, options); | |
var mapPositions = []; | |
for (var i = 0; i < markerPositions.length; i++) { | |
var markerPos = markerPositions[i]; | |
var position = new google.maps.LatLng(markerPos.lat, markerPos.long); | |
mapPositions[i] = position; | |
var infoWindow = new google.maps.InfoWindow({ | |
content: markerPos.description || markerPos.title, | |
position: position | |
}); | |
var marker = new google.maps.Marker({ | |
map: map, | |
position: position, | |
title: markerPos.title, | |
infoWindow: infoWindow | |
}); | |
google.maps.event.addListener(marker, 'click', function (e) { | |
this.infoWindow.open(map, this); | |
}); | |
} | |
// Fit to markers | |
var bounds = new google.maps.LatLngBounds(); | |
for (var i = 0; i < mapPositions.length; i++) { | |
bounds.extend(mapPositions[i]); | |
} | |
map.fitBounds(bounds); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment