google map marker is not pinning properly

2019-09-12 17:40发布

问题:

Code:

var dest1 = document.getElementById('textbox1').value;
var request = {
  origin:start,
  destination:dest1,
  travelMode: google.maps.TravelMode[selectedMode]
}

directionsService.route(request, function(response, status) {
  if (status == google.maps.DirectionsStatus.OK) {
    directionsDisplay1.setDirections(response);
  }
});

I am finding a location using google API and then calculating the distance between the searched place and the particular hotel which is coming from my data base, In image you can see i have searched for route map and distance for "Leela Palace Bengaluru, HAL Airport Road, ISRO Colony, Bengaluru, Karnataka, India" to my hotel which is coming from data base,as you can see the marker is not exactly pinning on leela palace instead it is showing next to the leela palace that is marked as B in image. I don't know where exactly i have done wrong it would be great if someone can help me with this thank you

Map response

回答1:

"Leela Palace Bengaluru, HAL Airport Road, ISRO Colony, Bengaluru, Karnataka, India" is a place, not a postal address. When you send that string to the geocoder you get a result for "Leela Palace Rd, HAL 3rd Stage, Bengaluru, Karnataka, India (12.9619947, 77.64936599999999)"

  • The geocoder is for postal addresses.
  • The Places API/library is for places.

The distance service uses the geocoder for strings, if you give it a place ID, it will use that for the destination.

Using the place id finder, the place id for "Leela Palace Bengaluru" is:

The Leela Palace Bengaluru

Place ID: ChIJ3ZvKfAYUrjsRGuckzDe-GxE

23, HAL Airport Rd, ISRO Colony, Domlur, Bengaluru, Karnataka 560008, India

You can use that for the destination of the DirectionsService.

proof of concept fiddle

code snippet:

var geocoder;
var map;

function initialize() {
  var map = new google.maps.Map(
    document.getElementById("map_canvas"), {
      center: new google.maps.LatLng(37.4419, -122.1419),
      zoom: 13,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });
  var start = "Jogupalya, Karnataka, India";
  var dest1 = {
    placeId: "ChIJ3ZvKfAYUrjsRGuckzDe-GxE"
  };
  var request = {
    origin: start,
    destination: dest1,
    travelMode: google.maps.TravelMode.DRIVING
  }
  var directionsService = new google.maps.DirectionsService();
  var directionsDisplay1 = new google.maps.DirectionsRenderer({
    map: map,
    preserveViewport: true
  });
  directionsService.route(request, function(response, status) {
    if (status == google.maps.DirectionsStatus.OK) {
      directionsDisplay1.setDirections(response);
      map.setCenter(response.routes[0].legs[0].end_location);
      map.setZoom(16);
    }
  });
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map_canvas"></div>