如何在我的 google 地图 api 网络中添加多个搜索框?

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

我正在尝试制作起点和终点菜单,因此用户将在每个输入中选择位置,并且每个输入都会在地图上添加一个标记,然后它会计算距离,这是我的进步到目前为止:我已经成功地添加了一个带有搜索框的地图,但我无法创建另一个地图,而且我不知道该怎么做。

这是我的代码:

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

一个选择是从 Autocomplete Directions Example in the documentation, change the Autocomplete objects to 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();
  });
};

添加计算返回路线长度的函数(来自问题: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

代码片段:

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