【问题标题】:How can I add multiple searchBoxes in my google maps api web?如何在我的 google maps api web 中添加多个搜索框?
【发布时间】:2019-11-23 05:13:40
【问题描述】:

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

这是我的代码:

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

【问题讨论】:

标签: javascript html google-maps-api-3


【解决方案1】:

一种选择是从文档中的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();
  });
};

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

代码 sn-p:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-08
    • 2013-06-28
    • 1970-01-01
    • 1970-01-01
    • 2021-09-02
    • 1970-01-01
    • 1970-01-01
    • 2013-03-14
    相关资源
    最近更新 更多