So, I guess you might populate said inputs from the backend, and provide a fallback in case they are null. Either way, you want to get a location and only then you want to instance your map.
The following should work:
var map;
function initialize() {
var createMapWithLocation=function(myposition) {
var mapOptions = {
zoom: 4,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: myposition
},
mymap = new google.maps.Map(document.getElementById("googlemap"), mapOptions),
marker = new google.maps.Marker({
position: myposition,
map: mymap,
draggable: true,
animation: google.maps.Animation.DROP
});
console.log('****' + myposition); //this should print third
return mymap;
};
var chicago = new google.maps.LatLng(51.508742, -0.120850); //default value
if (($("#latitude_val").val().length > 3) || ($("#longitude_val").val().length > 3)) {
chicago = new google.maps.LatLng($("#latitude_val").val(), $("#longitude_val").val());
map = createMapWithLocation(chicago);
} else {
geocoder = new google.maps.Geocoder();
geocoder.geocode({
'address': 'Abudhabi'
}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
console.log(results[0].geometry.location.lat() + ' ' + results[0].geometry.location.lng()); //if null this should print first
chicago = new google.maps.LatLng(results[0].geometry.location.lat(), results[0].geometry.location.lng());
console.log('__' + chicago); //this should print second
map = createMapWithLocation(chicago);
} else {
console.log("Geocode was not successful for the following reason: " + status);
}
});
}
}
You decide when to call createMapWithLocation
. It will be synchronous if the inputs are populated, and asynchronous if they aren't. Either way, you don't need to know the position of chicago beforehand.
Please note I've declared map outside of the initialize
function, just in case you want to inspect it from the console.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…