【问题标题】:How to get country, postal code, locality and sub-locality if address_component not provided in the places from google map?如果在谷歌地图的地方没有提供地址组件,如何获取国家、邮政编码、地区和子地区?
【发布时间】:2018-12-14 05:54:48
【问题描述】:
function getAddress(results){
var address = {};
  for (i = 0; i < results[0].address_components.length; ++i){
      for (j = 0; j < results[0].address_components[i].types.length; ++j)
      {
          if (!country && results[0].address_components[i].types[j] == "country")
              address.country = results[0].address_components[i].long_name;
          else if (!postal_code && results[0].address_components[i].types[j] == "postal_code")
              address.postal_code = results[0].address_components[i].long_name;
          else if (!locality && results[0].address_components[i].types[j] == "locality")
              address.locality = results[0].address_components[i].long_name;
          else if (!sublocality && results[0].address_components[i].types[j] == "sublocality")
              address.sublocality = results[0].address_components[i].long_name;
      }
  }
  return address;
}

我正在使用 google.map.places.SearchBox 来查找此结果。

但在许多情况下,结果是 10-12,但这些都不包含 component_address

搜索“j.m.d near Near Gill Chowk, Ludhiana, Punjab, India”,您将看到两个结果同时检查,一个包含零个结果,一个包含 5 个结果,但没有格式化的地址。

【问题讨论】:

    标签: javascript google-maps maps google-maps-api-2 street-address


    【解决方案1】:

    您可以使用SearchBox 返回的place_id 发出getDetails 请求来检索该地点的地址组件

    var service = new google.maps.places.PlacesService(map);
        service.getDetails({
          placeId: place.place_id
        }, function(place, status) {
          if (status === google.maps.places.PlacesServiceStatus.OK) {
            console.log(place);
            var marker = new google.maps.Marker({
              map: map,
              position: place.geometry.location
            });
            google.maps.event.addListener(marker, 'click', function() {
              var results = [place];
              var address = getAddress(results);
              infowindow.setContent('<div><strong>' + place.name + '</strong><br>' +
                'Place ID: ' + place.place_id + '<br>' +
                place.formatted_address + '</div>'+JSON.stringify(address));
              infowindow.open(map, this);
            });
            google.maps.event.trigger(marker, 'click');
          }
        });
    

    proof of concept fiddle

    code sn-p(不会返回位置结果,因为没有 API 密钥):

    // This example adds a search box to a map, using the Google Place Autocomplete
    // feature. People can enter geographical searches. The search box will return a
    // pick list containing a mix of places and predicted search terms.
    
    // This example requires the Places library. Include the libraries=places
    // parameter when you first load the API. For example:
    // <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places">
    
    function initAutocomplete() {
      var map = new google.maps.Map(document.getElementById('map'), {
        center: {
          lat: -33.8688,
          lng: 151.2195
        },
        zoom: 13,
        mapTypeId: 'roadmap'
      });
      var infowindow = new google.maps.InfoWindow();
      google.maps.event.addListener(map, 'click', function(e) {
        console.log(e.latLng.toUrlValue(6) + ":" + e.placeId)
      })
      // Create the search box and link it to the UI element.
      var input = document.getElementById('pac-input');
      var searchBox = new google.maps.places.SearchBox(input);
      map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
    
      // 30.911057,75.851275:ChIJF5htW6CDGjkRTzN_txBXtr4
      // Bias the SearchBox results towards current map's viewport.
      map.addListener('bounds_changed', function() {
        searchBox.setBounds(map.getBounds());
      });
    
      var markers = [];
      // Listen for the event fired when the user selects a prediction and retrieve
      // more details for that place.
      searchBox.addListener('places_changed', function() {
        var places = searchBox.getPlaces();
        console.log(places);
        if (places.length == 0) {
          return;
        }
    
        // Clear out the old markers.
        markers.forEach(function(marker) {
          marker.setMap(null);
        });
        markers = [];
    
        // For each place, get the icon, name and location.
        var bounds = new google.maps.LatLngBounds();
        places.forEach(function(place) {
          if (!place.geometry) {
            console.log("Returned place contains no geometry");
            return;
          }
          console.log(place);
          var icon = {
            url: place.icon,
            size: new google.maps.Size(71, 71),
            origin: new google.maps.Point(0, 0),
            anchor: new google.maps.Point(17, 34),
            scaledSize: new google.maps.Size(25, 25)
          };
    
          // Create a marker for each place.
          var marker = new google.maps.Marker({
            map: map,
            icon: icon,
            title: place.name,
            position: place.geometry.location
          });
          markers.push(marker);
          google.maps.event.addListener(marker, 'click', function() {
            infowindow.setContent('<div><strong>' + place.name + '</strong><br>' +
              'Place ID: ' + place.place_id + '<br>' +
              place.formatted_address + '</div>');
            infowindow.open(map, this);
            var service = new google.maps.places.PlacesService(map);
            service.getDetails({
              placeId: place.place_id
            }, function(place, status) {
              if (status === google.maps.places.PlacesServiceStatus.OK) {
                console.log(place);
                var marker = new google.maps.Marker({
                  map: map,
                  position: place.geometry.location
                });
                google.maps.event.addListener(marker, 'click', function() {
                  var results = [place];
                  var address = getAddress(results);
                  infowindow.setContent('<div><strong>' + place.name + '</strong><br>' +
                    'Place ID: ' + place.place_id + '<br>' +
                    place.formatted_address + '</div>' + JSON.stringify(address));
                  infowindow.open(map, this);
                });
                google.maps.event.trigger(marker, 'click');
              }
            });
          });
          if (places.length == 1)
            google.maps.event.trigger(marker, 'click')
          if (place.geometry.viewport) {
            // Only geocodes have viewport.
            bounds.union(place.geometry.viewport);
          } else {
            bounds.extend(place.geometry.location);
          }
        });
        map.fitBounds(bounds);
      });
    }
    
    function getAddress(results) {
      var country, postal_code, locality, sublocality;
      var address = {};
      for (i = 0; i < results[0].address_components.length; ++i) {
        for (j = 0; j < results[0].address_components[i].types.length; ++j) {
          if (!country && results[0].address_components[i].types[j] == "country")
            address.country = results[0].address_components[i].long_name;
          else if (!postal_code && results[0].address_components[i].types[j] == "postal_code")
            address.postal_code = results[0].address_components[i].long_name;
          else if (!locality && results[0].address_components[i].types[j] == "locality")
            address.locality = results[0].address_components[i].long_name;
          else if (!sublocality && results[0].address_components[i].types[j] == "sublocality")
            address.sublocality = results[0].address_components[i].long_name;
        }
      }
      console.log(address);
      return address;
    }
    /* Always set the map height explicitly to define the size of the div
     * element that contains the map. */
    
    #map {
      height: 100%;
    }
    
    
    /* Optional: Makes the sample page fill the window. */
    
    html,
    body {
      height: 100%;
      margin: 0;
      padding: 0;
    }
    
    #description {
      font-family: Roboto;
      font-size: 15px;
      font-weight: 300;
    }
    
    #infowindow-content .title {
      font-weight: bold;
    }
    
    #infowindow-content {
      display: none;
    }
    
    #map #infowindow-content {
      display: inline;
    }
    
    .pac-card {
      margin: 10px 10px 0 0;
      border-radius: 2px 0 0 2px;
      box-sizing: border-box;
      -moz-box-sizing: border-box;
      outline: none;
      box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
      background-color: #fff;
      font-family: Roboto;
    }
    
    #pac-container {
      padding-bottom: 12px;
      margin-right: 12px;
    }
    
    .pac-controls {
      display: inline-block;
      padding: 5px 11px;
    }
    
    .pac-controls label {
      font-family: Roboto;
      font-size: 13px;
      font-weight: 300;
    }
    
    #pac-input {
      background-color: #fff;
      font-family: Roboto;
      font-size: 15px;
      font-weight: 300;
      margin-left: 12px;
      padding: 0 11px 0 13px;
      text-overflow: ellipsis;
      width: 400px;
    }
    
    #pac-input:focus {
      border-color: #4d90fe;
    }
    
    #title {
      color: #fff;
      background-color: #4d90fe;
      font-size: 25px;
      font-weight: 500;
      padding: 6px 12px;
    }
    
    #target {
      width: 345px;
    }
    <input id="pac-input" class="controls" type="text" placeholder="Search Box" value="j.m.d near Near Gill Chowk, Ludhiana, Punjab, India">
    <div id="map"></div>
    <!-- Replace the value of the key parameter with your own API key. -->
    <script src="https://maps.googleapis.com/maps/api/js?libraries=places&callback=initAutocomplete" async defer></script>

    【讨论】:

      猜你喜欢
      • 2017-05-11
      • 2013-09-17
      • 2017-04-25
      • 1970-01-01
      • 2011-01-05
      • 2018-10-20
      • 2021-04-18
      • 2011-08-30
      • 1970-01-01
      相关资源
      最近更新 更多