使用变量设置google原始搜索框地址

问题描述 投票:0回答:1

我试图使原始 SearchBox 目的地成为具有合法方向的字符串,但是当我这样做时,我仍然需要选择第一个选项才能使其工作(以计算距离)。

通过此搜索来计算两点之间的距离,效果非常好: 如何在我的谷歌地图 API Web 中添加多个搜索框?

我有一个字符串,例如:albrook mall,我知道它存在(这个字符串是动态的,来自变量,并且所有地址都经过验证。获取所需的地址,将其传递给变量,以便我可以在前端读取它,然后设置html中搜索框的值。该值通过jquery更新

但是发生的情况是,我仍然必须单击原点搜索框,然后列出所有可能的位置,在我的情况下是第一个位置,如何使地图自动选择第一个选项或识别设置的地址在输入值中?

    <script>

   function initMap() {
   var map = new google.maps.Map(document.getElementById('map-canvas'), {
  center: {
  lat: 9.0271554,
   lng: 79.4816371
         },
         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.avoidTolls = true;
        this.avoidHighways= true;
          //this.provideRouteAlternatives= true,
          this.avoidFerries= true;
        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,
  avoidTolls: this.avoidTolls
   },
   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.
      time = (totalTime / 60).toFixed(2)

  document.getElementById("totalkm").innerHTML ="" + totalDist + "km" ;
  document.getElementById("totaltime").innerHTML ="" + time  + " minutos";

 if(totalDist <= 5){
   document.getElementById("totalCost").innerHTML =" $3.50";
  }

 else{
 kmPrice = (totalDist - 5) * 0.75;
 document.getElementById("totalCost").innerHTML ="$" +(kmPrice + 3.50).toFixed(2)+ "";

     }
    }

   function send_handle(){
   let name=document.getElementById("name").value;
 ///let lastname= document.getElementById("lastname").value;
 let inst= document.getElementById("instructions").value;
 let origin= document.querySelector(".selectButtons input#orign").value;
let destination= document.querySelector(".selectButtons input#destn").value;
let cost= document.getElementById("totalCost").innerHTML;
let distance= document.getElementById("totalkm").innerHTML;
    // win.focus();
     }
    </script>


           
    <html>
   <div class="selectButtons" >
   <input type="text" id="orign" placeholder="origen">
   <input type="text" id="destn" placeholder="destino">
   <span> Distancia en KM <div id="totalkm">0km</div> </span>
   <span> Distancia en tiempo <div id="totaltime">o.oo</div> </span>
   <span> costo por envio<div id="totalCost">$0</div></div> </span>
   </div>
   </html>
javascript html google-maps google-maps-api-3
1个回答
1
投票

您可以调用地方服务来获取 PlaceId (带有您的字符串),然后将该 placeId 传递到您的

AutocompleteDirectionsHandler
的构造函数中,或者如果您已经拥有
PlaceId
(您可以存储这些),则只需使用它,尽管您可能想用字符串初始化原始输入。

  var origin = "Allbrook, Panama";
  var originInput = document.getElementById('orign');
  originInput.value = origin;
  const request = {
    query: origin,
    fields: ["name", "geometry", "place_id"],
  };
  var originPlaceId;
  var service = new google.maps.places.PlacesService(map);
  service.findPlaceFromQuery(request, (results, status) => {
    if (status === google.maps.places.PlacesServiceStatus.OK && results) {
      originPlaceId = results[0].place_id;
      console.log("placeId="+originPlaceId+" coords="+results[0].geometry.location.toUrlValue(6));
      new AutocompleteDirectionsHandler(map, originPlaceId);
      map.setCenter(results[0].geometry.location);
    }
  });

将初始原点 placeId 添加到

AutocompleteDirectionsHandler
构造函数中:

function AutocompleteDirectionsHandler(map, originPlaceId) {
  this.map = map;
  this.originPlaceId = originPlaceId;
  // ...

加载时:

从下拉列表中选择目的地后:

代码片段:

let map;
function initMap() {
  map = new google.maps.Map(document.getElementById('map-canvas'), {
    center: {
      lat: 9.0271554,
      lng: 79.4816371
    },
    zoom: 15
  });

  var origin = "Allbrook, Panama";
  var originInput = document.getElementById('orign');
  originInput.value = origin;
  const request = {
    query: origin,
    fields: ["name", "geometry", "place_id"],
  };
  var originPlaceId;
  var service = new google.maps.places.PlacesService(map);
  service.findPlaceFromQuery(request, (results, status) => {
    if (status === google.maps.places.PlacesServiceStatus.OK && results) {
      originPlaceId = results[0].place_id;
      console.log("placeId="+originPlaceId+" coords="+results[0].geometry.location.toUrlValue(6));
      new AutocompleteDirectionsHandler(map, originPlaceId);
      map.setCenter(results[0].geometry.location);
    }
  });

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

/**
 * @constructor
 */
function AutocompleteDirectionsHandler(map, originPlaceId) {
  this.map = map;
  this.originPlaceId = originPlaceId;
  this.destinationPlaceId = null;
  this.travelMode = 'DRIVING';
  this.avoidTolls = true;
  this.avoidHighways = true;
  //this.provideRouteAlternatives= true,
  this.avoidFerries = true;
  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,
      avoidTolls: this.avoidTolls
    },
    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.
  time = (totalTime / 60).toFixed(2)

  document.getElementById("totalkm").innerHTML = "" + totalDist + "km";
  document.getElementById("totaltime").innerHTML = "" + time + " minutos";

  if (totalDist <= 5) {
    document.getElementById("totalCost").innerHTML = " $3.50";
  } else {
    kmPrice = (totalDist - 5) * 0.75;
    document.getElementById("totalCost").innerHTML = "$" + (kmPrice + 3.50).toFixed(2) + "";

  }
}

function send_handle() {
  let name = document.getElementById("name").value;
  ///let lastname= document.getElementById("lastname").value;
  let inst = document.getElementById("instructions").value;
  let origin = document.querySelector(".selectButtons input#orign").value;
  let destination = document.querySelector(".selectButtons input#destn").value;
  let cost = document.getElementById("totalCost").innerHTML;
  let distance = document.getElementById("totalkm").innerHTML;
  // win.focus();
}


function createMarker(place) {
  if (!place.geometry || !place.geometry.location) return;

  const marker = new google.maps.Marker({
    map,
    position: place.geometry.location,
  });

  google.maps.event.addListener(marker, "click", () => {
    infowindow.setContent(place.name || "");
    infowindow.open(map);
  });
}

window.initMap = initMap;
#map-canvas {
  height: 80%;
}


/* Optional: Makes the sample page fill the window. */

html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}
<html>
<div class="selectButtons">
  <input type="text" id="orign" placeholder="origen" />
  <input type="text" id="destn" placeholder="destino" />
  <span> Distancia en KM <div id="totalkm">0km</div> </span>
  <span> Distancia en tiempo <div id="totaltime">o.oo</div> </span>
  <span> costo por envio<div id="totalCost">$0</div> </span>
</div>
<div id="map-canvas"></div>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&libraries=places&callback=initMap" async defer></script>

</html>

© www.soinside.com 2019 - 2024. All rights reserved.