Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
520 views
in Technique[技术] by (71.8m points)

jquery - Google API Address Components

I am attempting to obtain the address components using the Google Maps API however am unable to properly parse results. My code is as follows:

    // Ajax Call
$.ajax({
    url: 'queryPage.php?',
    data: 'varObtainGoogleAddress=y&' +
          'varAPILink=' + encodeURIComponent(varAPILink),
    dataType: 'json',
    success: function(data) {   
        // Formatted Address
        varFormattedAddress = data.result['formatted_address'];  // Works!
    }
});

What I would like is the city, state and postal code items. Any help in this regard is appreciated. I am a self taught amateur web developer. :)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I wrote a function.

/**
*   geocodeResponse is an object full of address data.  
*   This function will "fish" for the right value
*   
*   example: type = 'postal_code' => 
*   geocodeResponse.address_components[5].types[1] = 'postal_code'
*   geocodeResponse.address_components[5].long_name = '1000'
* 
*   type = 'route' => 
*   geocodeResponse.address_components[1].types[1] = 'route'
*   geocodeResponse.address_components[1].long_name = 'Wetstraat'
*/
function addresComponent(type, geocodeResponse, shortName) {
  for(var i=0; i < geocodeResponse.address_components.length; i++) {
    for (var j=0; j < geocodeResponse.address_components[i].types.length; j++) {
      if (geocodeResponse.address_components[i].types[j] == type) {
        if (shortName) {
          return geocodeResponse.address_components[i].short_name;
        }
        else {
          return geocodeResponse.address_components[i].long_name;
        }
      }
    }
  }
  return '';
}

example of how to use:

...
myGeocoder.geocode({'latLng': marker.getPosition()}, function(results, status) {
  if (status == google.maps.GeocoderStatus.OK && results[1]) {
    var country = addresComponent('country', results[1], true);
    var postal_code = addresComponent('postal_code', results[1], true);
  }
});
...

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...