将Google Maps SearchBox结果传递给路线服务

时间:2015-12-14 15:19:08

标签: google-maps

在阅读SearchBox类,Places库(包括AutoComplete类)和Directions服务的文档后,我无法弄清楚如何将用户从SearchBox选择的地址传递给Directions服务以绘制地图。地图和标记正确显示,SearchBox正确显示和运行。在" place_change"但事件并没有发生。我的代码:

var rawlatitude = <?php echo $loc_lat; ?>;
var rawlongitude = <?php echo $loc_long; ?>;
var latitude = parseFloat(rawlatitude);
var longitude = parseFloat(rawlongitude);
var latlong = new google.maps.LatLng(latitude,longitude);

google.maps.event.addDomListener(window, 'load',initMap(latitude,longitude));

function initMap(lat,lng) {
    // instantiate directions service object
    var directionsService = new google.maps.DirectionsService;
    // create map
    var map = new google.maps.Map(document.getElementById('map'), {
        zoom: 16,
        center: latlong
    });
    // add marker
    var marker = new google.maps.Marker({
        position: latlong,
        map: map
    });
    // put address search box into map
    var input = document.getElementById('pac-input');
    var searchBox = new google.maps.places.SearchBox(input);
    map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
    // create directions renderer and bind it to map
    var directionsDisplay = new google.maps.DirectionsRenderer({map: map});
    // listen to and respond to address search
    var onChangeHandler = function() {
        var location = searchBox.getPlaces();
        var start = location.place_id;
        calculateAndDisplayRoute(directionsDisplay, directionsService, map, start);
    };
    google.maps.event.addListener(searchBox, 'place_change', onChangeHandler);
}

function calculateAndDisplayRoute(directionsDisplay, directionsService, map, start) {
    directionsService.route({
        origin: start,
        destination: latlong,
        travelMode: google.maps.TravelMode.DRIVING
    },  function(response, status) {
            if(status === google.maps.DirectionsStatus.OK) {
                directionsDisplay.setDirections(response);
            } else {
                window.alert('Directions request failed due to ' + status);
            }
    });
}

1 个答案:

答案 0 :(得分:0)

正如Dr.Molle在评论中所说,

  

SearchBox没有place_changed-event,它是自动完成的事件。 SearchBox的事件称为places_changed。

     

另请注意,SearchBox.getPlaces()返回带有地点的数组

working fiddle

工作代码段

var rawlatitude = 40.7127837;
var rawlongitude = -74.0059413;
var latitude = parseFloat(rawlatitude);
var longitude = parseFloat(rawlongitude);
var latlong = new google.maps.LatLng(latitude, longitude);
var viewport = {
  "south": 40.4960439,
  "west": -74.2557349,
  "north": 40.91525559999999,
  "east": -73.7002721
};

google.maps.event.addDomListener(window, 'load', function() {
  initMap(40.735657, -74.1723667);
});


function initMap(lat, lng) {
  // instantiate directions service object
  var directionsService = new google.maps.DirectionsService;
  // create map
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 16,
    center: latlong
  });
  // add marker
  var marker = new google.maps.Marker({
    position: latlong,
    draggable: true,
    map: map
  });
  // put address search box into map
  var input = document.getElementById('pac-input');
  var searchBox = new google.maps.places.SearchBox(input, {
    bounds: viewport
  });
  map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
  // create directions renderer and bind it to map
  var directionsDisplay = new google.maps.DirectionsRenderer({
    map: map
  });
  // listen to and respond to address search
  var onChangeHandler = function() {
    var locations = searchBox.getPlaces();

    var start = locations[0].place_id;
    var bounds = new google.maps.LatLngBounds();
    bounds.extend(latlong);
    bounds.extend(locations[0].geometry.location);
    map.fitBounds(bounds);
    var marker = new google.maps.Marker({
      position: locations[0].geometry.location,
      map: map,
      title: locations[0].name
    })
    calculateAndDisplayRoute(directionsDisplay, directionsService, map, start);
  };
  google.maps.event.addListener(searchBox, 'places_changed', onChangeHandler);
}

function calculateAndDisplayRoute(directionsDisplay, directionsService, map, start) {
  directionsService.route({
    origin: {
      placeId: start
    },
    destination: {
      location: latlong
    },
    travelMode: google.maps.TravelMode.DRIVING
  }, function(response, status) {
    if (status === google.maps.DirectionsStatus.OK) {
      directionsDisplay.setDirections(response);
    } else {
      window.alert('Directions request failed due to ' + status);
    }
  });
}
html,
body,
#map {
  height: 100%;
  width: 100%;
  margin: 0;
  padding: 0;
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>
<input id="pac-input" />
<div id="map"></div>