将Google地图搜索框结果传递给路线服务 [英] Pass Google Maps SearchBox result to Directions Service

查看:108
本文介绍了将Google地图搜索框结果传递给路线服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在阅读了SearchBox类,包括AutoComplete类和Directions服务的Places库文档后,我无法弄清楚如何将用户从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));

函数initMap(lat,lng){
//实例化路线服务对象
var directionsService = new google.maps.DirectionsService;
//创建地图
var map = new google.maps.Map(document.getElementById('map'),{
zoom:16,$ b $ center:latlong
});
//添加标记
var marker = new google.maps.Marker({
position:latlong,
map:map
});
//将地址搜索框放入地图
var input = document.getElementById('pac-input');
var searchBox = new google.maps.places.SearchBox(input);
map.controls [google.maps.ControlPosition.TOP_LEFT] .push(input);
//创建方向渲染器并将其绑定到地图
var directionsDisplay = new google.maps.DirectionsRenderer({map:map});
//监听并响应地址搜索
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);


函数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 requests failed to +'status');
}
});
}


解决方案

他的评论,


SearchBox没有place_changed-event,这是一个Autocomplete事件。 SearchBox的事件称为places_changed。



另请注意,SearchBox.getPlaces()返回一个包含位置的数组

工作小提琴



working code snippet:



<预类= 片段码-JS郎-JS prettyprint-越权> 变种rawlatitude = 40.7127837; VAR rawlongitude = -74.0059413; VAR纬度= parseFloat(rawlatitude); VAR经度= parseFloat(rawlongitude); VAR经纬度=新google.maps.LatLng(纬度,经度); VAR视= { 南:40.4960439, 西:-74.2557349, 北:40.91525559999999, 东: -73.7002721}; google.maps.event.addDomListener(window,'load',function(){initMap(40.735657,-74.1723667);});函数initMap(lat,lng){//实例化路线服务对象var directionsService =新的google.maps.DirectionsService; //创建地图var map = new google.maps.Map(document.getElementById('map'),{zoom:16,center:latlong}); //添加标记var marker = new google.maps.Marker({position:latlong,draggable:true,map: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(输入); //创建方向渲染器并将其绑定到地图var directionsDisplay = new google.maps.DirectionsRenderer({map:map}); //监听并响应地址搜索var onChangeHandler = function(){var locations = searchBox.getPlaces(); var start = locations [0] .place_id; var bounds = new google.maps.LatLngBounds(); bounds.extend(经纬度); bounds.extend(位置[0] .geometry.location); map.fitBounds(边界); 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(搜索框, 'places_changed',onChangeHandler);}函数calculateAndDisplayRoute(directionsDisplay,为DirectionsService,地图,启动){directionsService.route({起源:{placeId:启动},目的地:{位置:经纬度} ,travelMode:google.maps.TravelMode.DRIVING},function(response,status){if(status === google.maps.DirectionsStatus.OK){directionsDisplay.setDirections(response);} else {window.alert('Directions请求因'+ status'失败);}});}

html,body,#map {height:100%;宽度:100%;保证金:0; padding:0;}

< script src =https ://maps.googleapis.com/maps/api/js?libraries = places>< / script>< input id =pac-input/>< div id =map><<<< ; / div>


After reading documentation for the SearchBox class, the Places library including the AutoComplete class, and the Directions service, I cannot figure out how to pass the address selected by a user from the SearchBox to the Directions service to draw the map. The map and marker display correctly, and the SearchBox displays and functions correctly. On the "place_change" event, though, nothing happens. My code:

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

解决方案

As Dr.Molle observed in his comment,

There is no place_changed-event for a SearchBox, it's an event for Autocomplete. The event for a SearchBox is called places_changed.

Also note that a SearchBox.getPlaces() returns an array with places

working fiddle

working code snippet:

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>

这篇关于将Google地图搜索框结果传递给路线服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆