0

I developed the code for our website that a user can autocomplete the location field using google places API and calculate distance from google matrix API using the lat-long.

1- My Code for autocomplete the location

<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>

The problem is the above code is- it show the result with state and country like Eden Garden, Kolkata, West Bengal, India. My requirement is to show the result as Eden Garden, Kolkata and fill the input field as Eden Garden, Kolkata.

2- Calculate the Distance between this autocomplete place and a seller's lat-long . below is the code - $google_landmark refer to autocomplete google places

$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));
}

The google places show a result Eden Garden, Kolkata, West Bengal, India

but the

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

not return a result. please suggest what is the problem with my code or logic.

Thanks

waseem asgar
  • 664
  • 8
  • 20

2 Answers2

0

What I have read from your code above, you have a fixed position:

var map = new google.maps.Map(document.getElementById('map'), { center: {lat: 28.6315, lng: 77.2167}, zoom: 13 });

It might be the problem, that your lat and lng cannot get updated.

-Paul

Paul
  • 42
  • 1
  • 6
  • we are not saving the lat-lng of place. we just save the places as string in database and then get lat-long on run time through https://maps.googleapis.com/maps/api/geocode/json?address='.urlencode($google_landmark).'&sensor=false this API . – waseem asgar Dec 20 '16 at 12:02
0

Google geocoder API works effective only when it is given exact addresses. The problem with your second call is even though Eden Garderns, Kolakata, West Bengal, India is from an auto complete value provided by the Google places API, this place actually has an adress as Churchgate, Mumbai, Maharashtra 400020, India. If you pass this actual address to the Google geocoder API then you will be able to retrieve the lat/long.Instead of directly taking the auto fill value get the address from the place selected. (Google place API has a place detail request and you can get complete address through that).

Coder
  • 2,153
  • 1
  • 16
  • 21