I have just started working with the Google Maps API and Geocoding Service. I followed this tutorial and it was great.
Now I want to be able to create a map with a center based on a location ( "Vancvouer, BC" ) as opposed to latitude and longtitude as required when creating the map.
What I am trying to do is use a callback function named "initMap()" to initialize the map, and in that function I am creating a Geocoder object to get lang and long based on a location. ( "Vancvouer, BC" ).
Here's my initMap() function:
function initMap() {
var geocoder1 = new google.maps.Geocoder();
var center = getCenter(geocoder1, 'Vancouver, BC');
if(center != null) {
alert(center[0].geometry.location);
}
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 8,
center: {lat: -34.397, lng: 150.644}
});
}
This is how I am getting lang and long based on address:
function getCenter(geocoder, address) {
geocoder.geocode({'address': address}, function(results, status) {
if (status === google.maps.GeocoderStatus.OK) {
console.log(results);
var result = results[0].geometry.location.toJSON();
return result;
} else {
alert('Geocode was not successful for the following reason: ' + status);
// return null;
}
});
}
This will return a JSON object with the lat and lang I want, but when I try to access its values in initMap() using the if statement center is always undefined.
Once I am able to get the value for center I believe I would be able to set the center easy enough, but why I am not getting these values?
I think its a problem with scope and callback functions, but cant figure it out. Been stuck for a while, thought I'd reach out for help.
Thanks,
Matt
P.S. Let me know if you need any other info. First post on stackoverflow...