How to extract city name from results array returned by Google Maps API?

时间:2016-03-02 10:47:50

标签: javascript json google-maps

<script type="text/javascript">
 var GOOGLE_API_KEY = "mykey";
 var lat, lng;
 var geocoder;
 var geoCodingUrl;
 if (navigator.geolocation) {
  navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
 }
 function successFunction(position) {
   var lat = position.coords.latitude;
   var lng = position.coords.longitude;
   var geoCodingUrl = "https://maps.googleapis.com/maps/api/geocode/json?latlng=" + lat + "," + lng + "&key=" + GOOGLE_API_KEY;
console.log(geoCodingUrl); 

   var address = result.address_components[4].longname;
   if (address == "Mumbai, India") {
     window.location = "url";
   } 
   if(address == "Bangalore, India"){
     window.location = "url";
   } 
   if(address == "Jaipur, India") {
     window.location = "url";
   }
   else{
     window.location = "url";
   }
  }

 function errorFunction() {
 alert ("Geocoder failed");
}

</script>  

As per the Google Maps API docs, the geoCodingUrl should return a JSON array. How do I retrieve the city name from that array? The console gives an error that says result variable not found, how do I refer to the array that is returned?

1 个答案:

答案 0 :(得分:0)

假设你在这里使用jquery是代码

function successFunction(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
var geoCodingUrl = "https://maps.googleapis.com/maps/api/geocode/json? latlng=" + lat + "," + lng + "&key=" + GOOGLE_API_KEY;
$.ajax({
    url:geoCodingUrl,
    method:"GET",
    success:function(res){
     var result=res.results;
     var address = result[0].address_components[4].longname;
     if (address == "Mumbai, India") {
       window.location = "url";
     } 
     if(address == "Bangalore, India"){
       window.location = "url";
     } 
    if(address == "Jaipur, India") {
     window.location = "url";
    }
    else{
     window.location = "url";
     }
   }
})
}