如果Google地图上的地方未提供address_component,如何获取国家/地区,邮政编码,地区和次地区?

时间:2018-12-14 05:54:49

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

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

搜索“印度旁遮普邦卢迪亚纳卢吉亚纳(Lear Gill Chowk)附近的j.m.d”,您会看到两个结果都选中了,一个包含零个结果,一个包含5个结果,但没有格式化的地址。

1 个答案:

答案 0 :(得分:1)

您可以通过使用getDetails返回的place_id发出SearchBox请求来检索该地点的地址部分

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

screenshot of resulting map

代码段(由于没有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>