How to return address types from google maps geocode?

余生长醉 提交于 2019-12-11 01:07:27

问题


I am currently using the google maps api to geocode locations on the map and return the address of the street.

I currently return the address with the following code:

        function codeLatLng(markerPos) {
            geocoder.geocode({'latLng': markerPos}, function(results, status) {
              if (status == google.maps.GeocoderStatus.OK) {
                if (results[1]) {
                //Set markerAddress variable
                var markerAddress = results[0].formatted_address;
alert(markerAddress);
...

But what if I don't want to return the formatted address but a more detailed version using Address Component Types, how can I return certain address values like: http://code.google.com/apis/maps/documentation/geocoding/#Types

Help appreciated.


回答1:


May I ask, why are you checking for results[1] and then using results[0] (or is it just a typo I should ignore)?

As long as status is OK, there will be at least one result. Otherwise, status would be ZERO_RESULTS.

Anyway, you can use something like this:

function codeLatLng(markerPos) {
  geocoder.geocode({'latLng': markerPos}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      var markerAddress = results[0].address_components[0].long_name
          + ' (type: ' + results[0].address_components[0].types[0] + ')';
      alert(markerAddress);

You can play a lot with the whole address_components array, have fun! :)

For even more fun, have a look at the (source code of the) Google Maps API v3 Geocoder Tool at http://gmaps-samples-v3.googlecode.com/svn/trunk/geocoder/v3-geocoder-tool.html




回答2:


long_name is the full text description or name of the address component as returned by the Geocoder.

 function codeLatLng(markerPos) {
                geocoder.geocode({'latLng': markerPos}, function(results, status) {
                  if (status == google.maps.GeocoderStatus.OK) {
                    if (results[1]) {
                    //Set markerAddress variable
                    var markerAddress = results[0].long_name;
    alert(markerAddress);
...


来源:https://stackoverflow.com/questions/8942108/how-to-return-address-types-from-google-maps-geocode

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!