I am calculating latitude,longitude of all addresses of country i have in mysql DB using geocoder.geocode. I calculate lat,long successfully, even calculate the distance from my lat,long to all addresses lat,long and stored those distances in an array. but when i access the array it is empty, and console.log is printing all contents of array.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(getLatLon, showError);
}else{
console.log("Geo Location is not supported");
}
function getLatLon(position){
var lat = position.coords.latitude;
var lng = position.coords.longitude;
var country;
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(lat, lng);
geocoder.geocode({'latLng': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
country = results[7].address_components[0].long_name;
$.ajax({
url:"getLocations.php",
method:"POST",
dataType:"JSON",
data:{location:country},
success: function(data){
var i=0;
var length = data.length;
for(i;i<length;i++){
if(isNaN(data[i])){
var geocoder = new google.maps.Geocoder();
var address = data[i];
var distance = getDistance(address,latlng,data[i+1]);
// myLocations.push(distance);
}
}
// This console.log prints all data
console.log(myLocations);
// But this piece of code is not working
for(var iterations=0;iterations<myLocations.length;iterations++){
console.log(myLocations[iterations]);
}
}
});
}
}
});
}
function getDistance(address,latlng,index){
var distance;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK)
{
var newdata = new google.maps.LatLng(results[0].geometry.location.lat(),results[0].geometry.location.lng());
distance = (google.maps.geometry.spherical.computeDistanceBetween(newdata, latlng))*0.000621371;
var var1 = {distance: distance, index:index};
myLocations.push(var1);
}
});
return distance;
}
function showError(error){
switch(error.code) {
case error.PERMISSION_DENIED:
var img = $('.arrow');
img.css('display','none');
console.log("User denied the request for Geolocation.");
break;
case error.POSITION_UNAVAILABLE:
var img = $('.arrow');
img.css('display','none');
console.log("Location information is unavailable.");
break;
case error.TIMEOUT:
var img = $('.arrow');
img.css('display','none');
console.log("The request to get user location timed out.");
break;
case error.UNKNOWN_ERROR:
var img = $('.arrow');
img.css('display','none');
console.log("An unknown error occurred.");
break;
}
}
may be it work for some one else, I used setTimeout(function(){ alert(myLocations); }, 3000);
after page load and it printed out the entire array as i wanted.
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.