Reputation: 4480
I am trying to convert a zip code into lat and lng using geocoder. I looked at the Google Maps Api example and followed several tutorials, but for some reason for lat and lng it returns "". Here is my code.
(function(window, google, address) {
var geocoder = new google.maps.Geocoder();
var lat = "";
var lng = "";
geocoder.geocode({
'address': address
}, function(results, status) {
var test = results[0];
lat = results[0].geometry.location.lat(); // lat is still equal to ""
lng = results[0].geometry.location.lng(); // lng is still equal to ""
});
var options = {
center: {
lat: lat,
lng: lng
},
zoom: 5
},
element = document.getElementById('map-canvas')
var map = new google.maps.Map(element, options)
}(window, window.google, 98107));
html,
body,
#map-canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map-canvas"></div>
Upvotes: 4
Views: 9491
Reputation: 161404
The geocoder is asynchronous. You need to use the data returned in the callback function when/where it exists.
(function(window, google, address) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
'address': address
}, function(results, status) {
var options = {
center: results[0].geometry.location,
zoom: 5
},
element = document.getElementById('map-canvas')
var map = new google.maps.Map(element, options)
});
}(window, window.google, "98107"));
Another issue with the posted code is the address
passed into the geocoder must be a string (so "98107", not 98107), if it isn't the API generates the error: InvalidValueError: in property address: not a string
(function(window, google, address) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
'address': address
}, function(results, status) {
var options = {
center: results[0].geometry.location,
zoom: 5
},
element = document.getElementById('map-canvas')
var map = new google.maps.Map(element, options)
});
}(window, window.google, "98107"));
html,
body,
#map-canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map-canvas"></div>
Upvotes: 4
Reputation: 804
geocode() is an asynchronous function, and you need to wait for its callback to get the actual results.
In your code, you create the center object outside of the callback before the latitude and longitude values are even returned.
Try the following :
geocoder.geocode({
'address': address
}, function(results, status) {
var test = results[0];
var options = {
center: {
lat: results[0].geometry.location.lat(),
lng: results[0].geometry.location.lng()
},
zoom: 5
}
});
Upvotes: 1