Created
November 25, 2011 19:12
-
-
Save thoughtpunch/1394235 to your computer and use it in GitHub Desktop.
Google Maps API + Places AutoComplete JS
This file contains hidden or 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
$(document).ready(function() | |
{ | |
$('blockquote.text').expander(); | |
function initialize() { | |
var mapDiv = $('#map_canvas'); | |
var lat = mapDiv.data('latitude'), | |
lng = mapDiv.data('longitude'); | |
var mapOptions = { | |
center: new google.maps.LatLng(lat,lng), | |
zoom: 13, | |
mapTypeId: google.maps.MapTypeId.ROADMAP | |
}; | |
var map = new google.maps.Map(document.getElementById('map_canvas'), | |
mapOptions); | |
var input = document.getElementById('search'); | |
var autocomplete = new google.maps.places.Autocomplete(input); | |
autocomplete.bindTo('bounds', map); | |
var infowindow = new google.maps.InfoWindow(); | |
var marker = new google.maps.Marker({ | |
map: map | |
}); | |
google.maps.event.addListener(autocomplete, 'place_changed', function() { | |
infowindow.close(); | |
var place = autocomplete.getPlace(); | |
if (place.geometry.viewport) { | |
map.fitBounds(place.geometry.viewport); | |
} else { | |
map.setCenter(place.geometry.location); | |
map.setZoom(16); // Why 17? Because it looks good. | |
} | |
var image = new google.maps.MarkerImage( | |
place.icon, | |
new google.maps.Size(71, 71), | |
new google.maps.Point(0, 0), | |
new google.maps.Point(17, 34), | |
new google.maps.Size(35, 35)); | |
marker.setIcon(image); | |
marker.setPosition(place.geometry.location); | |
var address = ''; | |
if (place.address_components) { | |
address = [(place.address_components[0] && | |
place.address_components[0].short_name || ''), | |
(place.address_components[1] && | |
place.address_components[1].short_name || ''), | |
(place.address_components[2] && | |
place.address_components[2].short_name || '') | |
].join(' '); | |
} | |
infowindow.setContent('<div><strong>' + place.name + '</strong><br>' + address); | |
infowindow.open(map, marker); | |
google.maps.event.addListener(marker, 'click', function() { | |
return place | |
}); | |
}); | |
} | |
google.maps.event.addDomListener(window, 'load', initialize); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment