我正在尝试传递findPlaceFromQuery()
中的变量值。但它没有传递值。相反,我的函数返回初始化的值。我试着用谷歌搜索我自己,但我没有解决这个问题的办法。在其他函数中获取值是很常见的,但在这里是不可能的。我做了很多次,但它在findPlaceFromQuery()
中不起作用。此外,它也不适用于Geocode。
在脚本末尾的CCD_ 3函数中有一个变量名CCD_。我已将他的值设置为"none"作为默认值。并希望在findPlaceFromQuery()
中设置并返回check
的值。请帮帮我。我陷入了困境。
此外,请建议我是否可以用谷歌自动完成。
这是我的javascript代码。
<script type="text/javascript">
window.onload = initializeMap;
var map, geocoder, originInput, destinationInput, originLatLng, destinationLatLng;
function initializeMap() {
// var infoWindow;
map = new google.maps.Map(document.getElementById('map'), {
mapTypeControl: false,
center: {lat: -33.8688, lng: 151.2195},
zoom: 13
});
geocoder = new google.maps.Geocoder();
new AutocompleteDirectionsHandler(map);
}
function handleLocationError(browserHasGeolocation, infoWindow, pos) {
infoWindow.setPosition(pos);
infoWindow.setContent(browserHasGeolocation ?
'Error: The Geolocation service failed.' :
'Error: Your browser doesn't support geolocation.');
infoWindow.open(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);
originInput = document.getElementById('origin-input');
//var via1Input = document.getElementById('via1-input');
destinationInput = document.getElementById('destination-input');
var waypoint1 = document.getElementById('waypoint1');
var waypoint2 = document.getElementById('waypoint2');
var waypoint3 = document.getElementById('waypoint3');
// var modeSelector = document.getElementById('mode-selector');
var originAutocomplete = new google.maps.places.Autocomplete(originInput);
var waypoint1Autocomplete = new google.maps.places.Autocomplete(waypoint1);
var waypoint2Autocomplete = new google.maps.places.Autocomplete(waypoint2);
var waypoint3Autocomplete = new google.maps.places.Autocomplete(waypoint3);
// Specify just the place data fields that you need.
// console.log(originAutocomplete);
originAutocomplete.setFields(['place_id', 'types']);
var destinationAutocomplete = new google.maps.places.Autocomplete(destinationInput);
// console.log(destinationAutocomplete);
// Specify just the place data fields that you need.
destinationAutocomplete.setFields(['place_id', 'types']);
// waypoint1Autocomplete.setFields(['place_id']);
// waypoint2Autocomplete.setFields(['place_id']);
// waypoint3Autocomplete.setFields(['place_id']);
this.setupPlaceChangedListener(originAutocomplete, 'ORIG');
this.setupPlaceChangedListener(destinationAutocomplete, 'DEST');
// this.setupPlaceChangedListener(waypoint1Autocomplete, 'DEST');
// this.setupPlaceChangedListener(waypoint2Autocomplete, 'DEST');
// this.setupPlaceChangedListener(waypoint3Autocomplete, 'DEST');
}
AutocompleteDirectionsHandler.prototype.setupPlaceChangedListener = function(
autocomplete, mode) {
var me = this;
autocomplete.bindTo('bounds', this.map);
autocomplete.addListener('place_changed', function() {
var place = autocomplete.getPlace();
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;
}
// console.log(me);
me.route();
});
};
AutocompleteDirectionsHandler.prototype.route = function() {
if (!this.originPlaceId || !this.destinationPlaceId) {
return;
}
var me = this;
var waypts = [];
var checkboxArray = document.getElementById("waypoints");
if(waypoint1.value != ''){
waypts.push({
location: waypoint1.value,
stopover: true
});
}
if(waypoint2.value != ''){
waypts.push({
location: waypoint2.value,
stopover: true
});
}
if(waypoint3.value != ''){
waypts.push({
location: waypoint3.value,
stopover: true
});
}
//console.log(waypts);
this.directionsService.route(
{
origin: {'placeId': this.originPlaceId},
destination: {'placeId': this.destinationPlaceId},
waypoints: waypts,
optimizeWaypoints: true,
travelMode: this.travelMode
},
function(response, status) {
if (status === 'OK') {
me.directionsRenderer.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
};
var waypoint = 0;
function addVia()
{
waypoint++;
$('#via-'+waypoint).show();
$('#vialabel-'+waypoint).show();
//this.destinationPlaceId = null;
if(waypoint == 3)
{
$('#addvia').hide()
}
}
function onDestinationChange(data)
{
var pickupLocation = getZone(originInput.value);
var destinationLocation = getZone(destinationInput.value);
setTimeout(
function()
{
console.log(pickupLocation);
if(pickupLocation)
{
jQuery.ajax({
url : '/calculateroutecost',
type : "POST",
data : {_token: '{{ csrf_token() }}', pickupLocation:pickupLocation, destinationLocation:destinationLocation},
dataType : "json",
success:function(data)
{
// alert("SUCCESS");
alert(data.success);
}
});
}
else
{
alert("Please add a pickup location.");
}
}, 3000);
}
$("#booking-cost").submit(function(event){
event.preventDefault(); //prevent default action
var post_url = $(this).attr("action"); //get form action url
var request_method = $(this).attr("method"); //get form GET/POST method
var form_data = $(this).serialize(); //Encode form elements for submission
$.ajax({
url : post_url,
type: request_method,
data : form_data
}).done(function(response){
});
});
var iii = 0;
function getZone(pAddress) {
var myLatLng, pickupLatLng, check = 'none', result;
const zoneCoords = {!! json_encode($json) !!};
const outerCoords = zoneCoords['outer'];
const innerCoords = zoneCoords['inner'];
const zone = new google.maps.Polygon({
paths: [outerCoords, innerCoords]
});
const request = {
query: pAddress,
fields: ["geometry"]
};
service = new google.maps.places.PlacesService(map);
service.findPlaceFromQuery(request, (results, status) => {
if (status === google.maps.places.PlacesServiceStatus.OK) {
pickupLatLng = new google.maps.LatLng(results[0].geometry.location.lat(), results[0].geometry.location.lng());
result = google.maps.geometry.poly.containsLocation(
pickupLatLng,
zone
)
? check = 'yes'
: check = 'no';
return check;
}
return check;
});
// var geocoder = new google.maps.Geocoder();
// var address = pAddress;
// var myLoc;
// var latlng = [];
// var output;
// geocoder.geocode( { 'address': address}, function(results, status) {
// if (status == google.maps.GeocoderStatus.OK) {
// myLoc = new google.maps.LatLng(results[0].geometry.location.lat(), results[0].geometry.location.lng());
// latlng[0] = results[0].geometry.location.lat();
// latlng[1] = results[0].geometry.location.lng();
// output = latlng[0] + ', ' + latlng[1];
// return myLoc;
// }
// });
return check;
}
</script>
由于您想要使用位置自动完成,您最终会有利益冲突。原因是,自动完成与位置详细信息一起使用,而不是与查找位置一起使用。"查找位置"SKU的成本与"自动完成"one_answers"位置详细信息"SKU的总和相似。请参阅价格表以供参考。
以下代码使用Places Autocomplete with Place Details and Directions API服务。
Place Details包括setFields可选参数,只获取您需要的数据,这样您就不会因任何不使用的数据而被计费。您可以在这里了解更多关于如何实现这一点的信息。有关可用字段的列表,请参阅此处。
以下代码的链接如下:https://jsfiddle.net/pintsik999/pky8a964/2/
HTML:
<!DOCTYPE html>
<html>
<head>
<title>Simple Map</title>
<script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
<!--Replace the key placeholder with your actual API Key-->
<script
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initializeMap&&libraries=places&v=weekly"
defer
></script>
</head>
<body>
<div id="floating-panel">
<input id="origin" type="textbox">
<input id="destination" type="textbox">
<input id="submit" type="button" value="Get Directions">
</div>
<div id="map"></div>
</body>
</html>
CSS:
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
#floating-panel {
position: absolute;
top: 10px;
left: 25%;
z-index: 5;
background-color: #fff;
padding: 5px;
border: 1px solid #999;
text-align: center;
font-family: 'Roboto', 'sans-serif';
line-height: 30px;
padding-left: 10px;
}
Javascript:
var map, selected_origin, selected_destination;
function initializeMap() {
map = new google.maps.Map(document.getElementById('map'), {
mapTypeControl: false,
center: {lat: -33.8688, lng: 151.2195},
zoom: 13
});
//Call the function for the autocomplete and place details service
new AutocompleteHandler();
document.getElementById('submit').addEventListener('click', function() {
DirectionsHandler();
});
}
function AutocompleteHandler() {
//Learn more about Places Autocomplete here: https://developers.google.com/maps/documentation/javascript/places-autocomplete
const originInput = document.getElementById("origin");
const destinationInput = document.getElementById("destination");
var autocomplete_origin = new google.maps.places.Autocomplete(originInput);
var autocomplete_destination = new google.maps.places.Autocomplete(destinationInput);
//add .setfields so that you will only get the data that you need to prevent additional costs
//Here is the list of available fields that you can use: https://developers.google.com/places/web-service/place-data-fields
autocomplete_origin.setFields(["formatted_address"]);
autocomplete_destination.setFields(["formatted_address"]);
// Set a listener to the autocomplete to get the details of the selected place
//learn more about how to get the place information here: https://developers.google.com/maps/documentation/javascript/places-autocomplete#get-place-information
autocomplete_origin.addListener("place_changed", () => {
selected_origin = autocomplete_origin.getPlace();
});
autocomplete_destination.addListener("place_changed", () => {
selected_destination = autocomplete_destination.getPlace();
});
}
function DirectionsHandler(){
// Learn more about the Directions Service here: https://developers.google.com/maps/documentation/javascript/directions#DirectionsRequests
const directionsService = new google.maps.DirectionsService();
const directionsRenderer = new google.maps.DirectionsRenderer();
directionsRenderer.setMap(map);
directionsService.route(
{
origin: {
query: selected_origin.formatted_address
},
destination: {
query: selected_destination.formatted_address
},
travelMode: google.maps.TravelMode.DRIVING
},
(response, status) => {
if (status === "OK") {
directionsRenderer.setDirections(response);
} else {
window.alert("Directions request failed due to " + status);
}
}
);
}
如果你也试图使用浏览器的地理定位服务与谷歌地图API,你可以参考这里的HTML 5地理定位