简体   繁体   English

如何在我的 google maps api web 中添加多个搜索框?

[英]How can I add multiple searchBoxes in my google maps api web?

I'm trying to make a origin and destination menu, so the user will choose the locations in each input, and each input will add a marker to the map and then it will calculate the distance, this is my progress so far: I've successfully added a map with a search box, but I can't create another one and I don't know how to do this.我正在尝试制作一个起点和目的地菜单,因此用户将在每个输入中选择位置,每个输入都会在地图上添加一个标记,然后它会计算距离,这是我到目前为止的进度:我我已成功添加了带有搜索框的地图,但我无法创建另一个地图,也不知道如何执行此操作。

This is my code:这是我的代码:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=MY_API_KEY&libraries=places"></script>
<div style="background-color: #FFC012">
<input type="text" id="orign" placeholder="origin">
<input type="text" id="destn" placeholder="destination">
<br>
<div id="map-canvas">
    <script>

var map = new google.maps.Map(document.getElementById('map-canvas'),{
  center:{
     lat: 19.4978,
     lng: -99.1269
 },
 zoom:15
 });

 var marker = new google.maps.Marker({
 map:map,
 draggable: false
 });


 if (navigator.geolocation) {
 navigator.geolocation.getCurrentPosition(function (position) {
   initialLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
   map.setCenter(initialLocation);
   /*marker.setPosition(initialLocation);         */
 });
 }


var searchBox = new google.maps.places.SearchBox(document.getElementById('orign'));

google.maps.event.addListener(searchBox, 'places_changed',function(){

var places = searchBox.getPlaces();

var bounds = new google.maps.LatLngBounds();
var i, place;

for(i=0; place=places[i];i++){
  bounds.extend(place.geometry.location);
  marker.setPosition(place.geometry.location);
}
map.fitBounds(bounds);
map.setZoom(15);
})



</script>
</div>
</div>

 var start,end; for(i=0; i < places.length;i++){ var place = places[i]; bounds.extend(place.geometry.location); marker.setPosition(place.geometry.location); if ( i == 0 ) start = place.geometry.location; else end = place.geometry.location; } find the lat long from the start and end locations with four variables like lat1, lon1, lat2, lon2 and pass the parameters in the function with unit K or N function distance(lat1, lon1, lat2, lon2, unit) { if ((lat1 == lat2) && (lon1 == lon2)) { return 0; } else { var radlat1 = Math.PI * lat1/180; var radlat2 = Math.PI * lat2/180; var theta = lon1-lon2; var radtheta = Math.PI * theta/180; var dist = Math.sin(radlat1) * Math.sin(radlat2) + Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta); if (dist > 1) { dist = 1; } dist = Math.acos(dist); dist = dist * 180/Math.PI; dist = dist * 60 * 1.1515; if (unit=="K") { dist = dist * 1.609344 } if (unit=="N") { dist = dist * 0.8684 } return dist; } } 

One option would be to start from the Autocomplete Directions Example in the documentation, change the Autocomplete objects to SearchBox objects, and the associated code to account for the differences ( SearchBox has a places_changed event, Autocomplete has place_changed (singular); the routine to get the results also has a different name (singular vs. plural).一种选择是从文档中的Autocomplete Directions Example开始,将Autocomplete对象更改为SearchBox对象,以及相关的代码来说明差异( SearchBox有一个places_changed事件, Autocompleteplace_changed (单数);获取的例程结果也有不同的名称(单数与复数)。

/**
 * @constructor
 */
function AutocompleteDirectionsHandler(map) {
  this.map = map;
  this.originPlaceId = null;
  this.destinationPlaceId = null;
  this.travelMode = 'DRIVING';
  this.directionsService = new google.maps.DirectionsService();
  this.directionsRenderer = new google.maps.DirectionsRenderer();
  this.directionsRenderer.setMap(map);

  var originInput = document.getElementById('orign');
  var destinationInput = document.getElementById('destn');

  var originAutocomplete = new google.maps.places.SearchBox(originInput);

  var destinationAutocomplete =
    new google.maps.places.SearchBox(destinationInput);

  this.setupPlaceChangedListener(originAutocomplete, 'ORIG');
  this.setupPlaceChangedListener(destinationAutocomplete, 'DEST');

}


AutocompleteDirectionsHandler.prototype.setupPlaceChangedListener = function(
  autocomplete, mode) {
  var me = this;
  autocomplete.bindTo('bounds', this.map);

  autocomplete.addListener('places_changed', function() {
    var places = autocomplete.getPlaces();
    var place = places[0];

    if (!place.place_id) {
      window.alert('Please select an option from the dropdown list.');
      return;
    }
    if (mode === 'ORIG') {
      me.originPlaceId = place.place_id;
    } else {
      me.destinationPlaceId = place.place_id;
    }
    me.route();
  });
};

Add a function to calculate the length of the returned route (from the question: Google Maps API: Total distance with waypoints ):添加一个函数来计算返回路线的长度(来自问题: Google Maps API: Total distance with waypoints ):

function computeTotalDistance(result) {
  var totalDist = 0;
  var totalTime = 0;
  var myroute = result.routes[0];
  for (i = 0; i < myroute.legs.length; i++) {
    totalDist += myroute.legs[i].distance.value;
    totalTime += myroute.legs[i].duration.value;
  }
  totalDist = totalDist / 1000.
  document.getElementById("total").innerHTML = "total distance is: " + totalDist + " km<br>total time is: " + (totalTime / 60).toFixed(2) + " minutes";
}

proof of concept fiddle概念证明小提琴

结果地图的屏幕截图

code snippet:代码片段:

 // This example requires the Places library. Include the libraries=places // parameter when you first load the API. For example: // <script // src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places"> function initMap() { var map = new google.maps.Map(document.getElementById('map-canvas'), { center: { lat: 19.4978, lng: -99.1269 }, zoom: 15 }); var marker = new google.maps.Marker({ map: map, draggable: false }); if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(function(position) { initialLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude); map.setCenter(initialLocation); /*marker.setPosition(initialLocation); */ }); } new AutocompleteDirectionsHandler(map); } /** * @constructor */ function AutocompleteDirectionsHandler(map) { this.map = map; this.originPlaceId = null; this.destinationPlaceId = null; this.travelMode = 'DRIVING'; this.directionsService = new google.maps.DirectionsService(); this.directionsRenderer = new google.maps.DirectionsRenderer(); this.directionsRenderer.setMap(map); var originInput = document.getElementById('orign'); var destinationInput = document.getElementById('destn'); var originAutocomplete = new google.maps.places.SearchBox(originInput); var destinationAutocomplete = new google.maps.places.SearchBox(destinationInput); this.setupPlaceChangedListener(originAutocomplete, 'ORIG'); this.setupPlaceChangedListener(destinationAutocomplete, 'DEST'); } AutocompleteDirectionsHandler.prototype.setupPlaceChangedListener = function( autocomplete, mode) { var me = this; autocomplete.bindTo('bounds', this.map); autocomplete.addListener('places_changed', function() { var places = autocomplete.getPlaces(); var place = places[0]; if (!place.place_id) { window.alert('Please select an option from the dropdown list.'); return; } if (mode === 'ORIG') { me.originPlaceId = place.place_id; } else { me.destinationPlaceId = place.place_id; } me.route(); }); }; AutocompleteDirectionsHandler.prototype.route = function() { if (!this.originPlaceId || !this.destinationPlaceId) { return; } var me = this; this.directionsService.route({ origin: { 'placeId': this.originPlaceId }, destination: { 'placeId': this.destinationPlaceId }, travelMode: this.travelMode }, function(response, status) { if (status === 'OK') { me.directionsRenderer.setDirections(response); computeTotalDistance(response); } else { window.alert('Directions request failed due to ' + status); } }); }; // from Google Maps API: Total distance with waypoints // https://stackoverflow.com/questions/12802202/google-maps-api-total-distance-with-waypoints function computeTotalDistance(result) { var totalDist = 0; var totalTime = 0; var myroute = result.routes[0]; for (i = 0; i < myroute.legs.length; i++) { totalDist += myroute.legs[i].distance.value; totalTime += myroute.legs[i].duration.value; } totalDist = totalDist / 1000. document.getElementById("total").innerHTML = "total distance is: " + totalDist + " km<br>total time is: " + (totalTime / 60).toFixed(2) + " minutes"; }
 /* Always set the map height explicitly to define the size of the div * element that contains the map. */ #map-canvas { height: 80%; } /* Optional: Makes the sample page fill the window. */ html, body { height: 100%; margin: 0; padding: 0; }
 <div style="background-color: #FFC012; height:100%; width:100%;"> <input type="text" id="orign" placeholder="origin" value="Lindavista Vallejo III Secc"> <input type="text" id="destn" placeholder="destination" value="Lienzo Charro de La Villa"> <div id="total"></div> <br> <div id="map-canvas"></div> </div> <!-- Replace the value of the key parameter with your own API key. --> <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&libraries=places&callback=initMap" async defer></script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM