Reputation: 29
I´m new to StackOverflow, so if I make a mistake, please be lenient with me.
I have a problem. When I am trying to access to a variable from another function, it results "null".
function initAutocomplete() {
var latitude = 0;
var longitude = 0;
var geocoder = new google.maps.Geocoder();
var address = document.getElementById("geocode").value;
geocoder.geocode({ 'address': address },
function getCoordinates(results, status) {
//if (status == google.maps.GeocoderStatus.OK) {
latitude = results[0].geometry.location.lat();
longitude = results[0].geometry.location.lng();
}
//}
);
var uluru = {lat: latitude,
lng: longitude};
var map = new google.maps.Map
(document.getElementById('map'),
{
center: uluru,
zoom: 17,
mapTypeId: 'roadmap'
});
}
Upvotes: 1
Views: 121
Reputation: 16458
From doc of Google Geocoding Service
Accessing the Geocoding service is asynchronous
This means that your function is called after the inizialization of uluru
object.
You should inizialize the map and uluru
object inside the function getCoordinates
Upvotes: 0
Reputation: 59
Simple example of accessing variables:
<script>
var a = 10;
var c;
function aa() {
document.write("func aa ");
var b = 20;
c = b;
document.write(a + b);
}
function bb() {
document.write("func bb ");
document.write(c);
}
aa();
document.write(" ");
bb();
Upvotes: 0
Reputation: 33813
latitude and longitude for uluru
are fully populated in the geocoding callback function which is not necessarily going to make them available when the function loads so instead you could use the callback to set the map center when those values are available.
function initAutocomplete() {
var latitude = 0;
var longitude = 0;
var uluru = {lat: latitude, lng: longitude };
var geocoder = new google.maps.Geocoder();
var address = document.getElementById("geocode").value;
geocoder.geocode({'address':address}, function getCoordinates( results, status ) {
if( status == google.maps.GeocoderStatus.OK ) {
latitude = results[0].geometry.location.lat();
longitude = results[0].geometry.location.lng();
map.setCenter( new google.maps.LatLng( latitude,longitude ) ;
}
});
var map = new google.maps.Map(document.getElementById('map'), {
center: uluru,
zoom: 17,
mapTypeId: 'roadmap'
});
}
Upvotes: 1