【问题标题】:Search By Google Place Autocomplete and get the distance from google matrix API通过 Google Place Autocomplete 搜索并获取与 google matrix API 的距离
【发布时间】:2017-05-05 07:39:16
【问题描述】:

我为我们的网站开发了代码,用户可以使用 google places API 自动完成位置字段,并使用 lat-long 计算与 google matrix API 的距离。

1- 用于自动完成位置的我的代码

<script>
var frm_ggl_dd = 1;
function initMap() {    
var options = {
    /*types: ['(cities)'],
    regions:['(locality,sublocality,postal_code)'],*/
    componentRestrictions: {country: "in"}
};


var map = new google.maps.Map(document.getElementById('map'), {
  center: {lat: 28.6315, lng: 77.2167},
  zoom: 13
});
var input = /** @type {!HTMLInputElement} */(
    document.getElementById('pac-input'));

var types = document.getElementById('type-selector');
//map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
map.controls[google.maps.ControlPosition.TOP_LEFT].push(types);

var autocomplete = new google.maps.places.Autocomplete(input,options);
autocomplete.bindTo('bounds', map);

var infowindow = new google.maps.InfoWindow();
var marker = new google.maps.Marker({
  map: map,
  anchorPoint: new google.maps.Point(0, -29)
});

autocomplete.addListener('place_changed', function() {
  frm_ggl_dd = 1;
  infowindow.close();
  marker.setVisible(false);
  var place = autocomplete.getPlace();
  if (!place.geometry) {
    window.alert("Autocomplete's returned place contains no geometry");
    return;
  }

  // If the place has a geometry, then present it on a map.
  if (place.geometry.viewport) {
    map.fitBounds(place.geometry.viewport);
  } else {
    map.setCenter(place.geometry.location);
    map.setZoom(17);  // Why 17? Because it looks good.
  }

  /*setting hidden field value so that have idea getting from google database*/
  /* $('#frmGoogleDB').val(1); */

  marker.setIcon(/** @type {google.maps.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(35, 35)
  }));
  marker.setPosition(place.geometry.location);
  marker.setVisible(true);

  var address = '';
  if (place.address_components) {
    address = [
      (place.address_components[0] && place.address_components[0].short_name || ''),
      (place.address_components[1] && place.address_components[1].short_name || ''),
      (place.address_components[2] && place.address_components[2].short_name || '')
    ].join(' ');
  }

  infowindow.setContent('<div><strong>' + place.name + '</strong><br>' + address);
  infowindow.open(map, marker);
});

// Sets a listener on a radio button to change the filter type on Places
// Autocomplete.
function setupClickListener(id, types) {
  var radioButton = document.getElementById(id);
  radioButton.addEventListener('click', function() {
    autocomplete.setTypes(types);
  });
}

setupClickListener('changetype-all', []);
setupClickListener('changetype-address', ['address']);
setupClickListener('changetype-establishment', ['establishment']);
setupClickListener('changetype-geocode', ['geocode']);
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDem6tqqXGpyvFNmgIdVIsmg3VlPZxAwe8&libraries=places&callback=initMap" async defer></script>

问题是上面的代码是 - 它显示了像 Eden Garden, Kolkata, West Bengal, India 这样的州和国家/地区的结果。我的要求是将结果显示为 Eden Garden, Kolkata 并将输入字段填写为 Eden Garden, Kolkata

2- 计算此自动填充位置与卖家的 lat-long 之间的距离。下面是代码 - $google_landmark 指的是自动完成的 google 地方

$api_url = 'https://maps.googleapis.com/maps/api/geocode/json?address='.urlencode($google_landmark).'&sensor=false';

            $geo = file_get_contents($api_url);
            $geoDecoded = json_decode($geo, true);      
            if ($geoDecoded['status'] = 'OK') {
                $latitude = $geoDecoded['results'][0]['geometry']['location']['lat'];
                $longitude = $geoDecoded['results'][0]['geometry']['location']['lng'];
                //echo $latitude.'-'.$longitude.'<br/>';
                $distance = $this->getMaxDistance($latitude, $longitude, $arrVenLatLng);     
            }

public function getMaxDistance($CustLatitude, $CustLongitude, $arrVenLatLng){
     $arrDistance = array();

     for($i=0; $i<count($arrVenLatLng); $i++){
        $geoDist = file_get_contents('https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins='.$CustLatitude.','.$CustLongitude.'&destinations='.$arrVenLatLng[$i]['lat'].','.$arrVenLatLng[$i]['long'].'&key=AIzaSyBV8Dbe9bMAK35VmLUSN30xXivN7ICVvsg');
        $geoDist = json_decode($geoDist, true);     

        if($geoDist['status'] = 'OK'){
            $arrDistance[] = $geoDist['rows'][0]['elements'][0]['distance']['value']/1000;
        }
     }

     return ceil(max($arrDistance));
}

Google 地方展示了一个结果Eden Garden, Kolkata, West Bengal, India

但是

'https://maps.googleapis.com/maps/api/geocode/json?address=Eden Garden, Kolkata, West Bengal, India&sensor=false';

不返回结果。请提出我的代码或逻辑有什么问题。

谢谢

【问题讨论】:

    标签: google-maps google-places-api google-place-report


    【解决方案1】:

    Google 地理编码器 API 仅在提供准确地址时才有效。您的第二个电话的问题是,即使 Eden Garderns, Kolakata, West Bengal, India 来自 Google Places API 提供的自动完成值,这个 place 实际上有一个地址为 Churchgate, Mumbai, Maharashtra 400020, India。如果您将此实际地址传递给 Google 地理编码器 API,那么您将能够检索纬度/经度。而不是直接获取自动填充值,而是从所选位置获取 地址。 (Google place API 有一个地点详情请求,您可以通过它获得完整的地址)。

    【讨论】:

      【解决方案2】:

      我从你上面的代码中读到的,你有一个固定的位置:

      var map = new google.maps.Map(document.getElementById('map'), { 中心:{纬度:28.6315,液化天然气:77.2167}, 缩放:13 });

      这可能是问题所在,您的 lat 和 lng 无法更新。

      -保罗

      【讨论】:

      猜你喜欢
      • 2019-10-04
      • 1970-01-01
      • 1970-01-01
      • 2020-08-10
      • 2019-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多