Get definite City name in Google maps reverse geocoding

前端 未结 3 605
野的像风
野的像风 2021-01-03 01:05

Using the Google Maps Geocoding API, i\'m able to get the formatted address for a particular coordinate. To get the exact city name, I\'m doing the following:



        
3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-03 01:44

    So I was trying to figure this out today and I came to this solution if it helps anyone. Google maps comes with the Geocoder built in now so you just create a geocoder object once the API has loaded.

    You can easily wrap that in a function and just return an object with the city, state, and postal code. This site was helpful in allowing me to see what the different 'types' mean: Reverse Geocoding

    var geocoder = new google.maps.Geocoder,
        latitude = 28.54, //sub in your latitude
        longitude = -81.39, //sub in your longitude
        postal_code,
        city,
        state;
    geocoder.geocode({'location': {lat:latitude, lng:longitude}}, function(results, status) {
      if (status === google.maps.GeocoderStatus.OK) {
        results.forEach(function(element){
          element.address_components.forEach(function(element2){
            element2.types.forEach(function(element3){
              switch(element3){
                case 'postal_code':
                  postal_code = element2.long_name;
                  break;
                case 'administrative_area_level_1':
                  state = element2.long_name;
                  break;
                case 'locality':
                  city = element2.long_name;
                  break;
              }
            })
          });
        });
      }
    });
    

提交回复
热议问题