I am trying to implement the Google API maps in my javascript. Based on an address, I want to get the corresponding latitude/longitude and show a map on this location. When I hardcode the location, it works. When I use the values from the geocoder, the map is empty. Here is the code:
<script>
function initMap() {
var loc = [];
var geocoder = new google.maps.Geocoder();
var address = "New York";
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
loc[0] = results[0].geometry.location.lat();
loc[1] = results[0].geometry.location.lng();
alert(loc);
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
// Create a map object and specify the DOM element for display.
var map = new google.maps.Map(document.getElementById('map'), {
center: { lat: loc[0], lng: loc[1] },
scrollwheel: false,
zoom: 8
});
}
</script>
The alert(loc) function displays the correct latitude and longitude values, but the map still seems to be empty. Any idea why?
The geocoder.geocode()
works asynchronously. That means you should put map initialization inside the callback function. Currently you initialize the map before the geocoder callback is triggered.
function initMap() {
var map;
var loc = [];
var geocoder = new google.maps.Geocoder();
var address = "New York";
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
loc[0] = results[0].geometry.location.lat();
loc[1] = results[0].geometry.location.lng();
//alert(loc);
// Create a map object and specify the DOM element for display.
map = new google.maps.Map(document.getElementById('map'),
{
center: { lat: loc[0], lng: loc[1] },
scrollwheel: false,
zoom: 8
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
Hope this helps!