I think I'm just doing something stupid because my javascript skills aren't the greatest. The following code produces a blank, gray map:
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
geocoder = new google.maps.Geocoder();
var address = "Minneapolis, MN";
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK)
{
lat = results[0].geometry.location.lat();
lng = results[0].geometry.location.lng();
addresslatlng = new google.maps.LatLng(results[0].geometry.location.lat(),results[0].geometry.location.lng());
}
else
{
alert(status);
}
});
var mapOptions = {
zoom: 7,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: addresslatlng
};
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('directions-panel'));
}
However, if simply change the "center: addresslatlng" to:
center: new google.maps.LatLng(-34.397, 150.644)
It works fine.
I tried using lat and lng and that does NOT work either:
center: new google.maps.LatLng(lat, lng)
Any ideas?
Geocoding is asynchronous. You need to use the results inside the call back function:
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
geocoder = new google.maps.Geocoder();
var address = "Minneapolis, MN";
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK)
{
lat = results[0].geometry.location.lat();
lng = results[0].geometry.location.lng();
addresslatlng = new google.maps.LatLng(results[0].geometry.location.lat(),results[0].geometry.location.lng());
var mapOptions = {
zoom: 7,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: addresslatlng
};
var map = new google.maps.Map(document.getElementById('map_canvas'),
mapOptions);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('directions-panel'));
}
else
{
alert(status);
}
});
}
I think this
lat = results[0].geometry.location.lat();
lng = results[0].geometry.location.lng();
really should be more like this
lat = results[0].geometry.location.lat;
lng = results[0].geometry.location.lng;
Also you create lat
and lon
and then don't use them in next line. Change this
addresslatlng = new google.maps.LatLng(results[0].geometry.location.lat(),results[0].geometry.location.lng());
to this
addresslatlng = new google.maps.LatLng(lat, lng);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.