function getCoords(position)
{
var longitude = position.coords.latitude;
var latitude = position.coords.longitude;
var coords = new google.maps.LatLng(latitude, longitude);
alert(coords);
});
}
这是初始化函数,我首次需要变量coords
:
function initMap()
{
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 22.5726, lng: 88.3639},
zoom: 13
});
infoWindow = new google.maps.InfoWindow;
// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position)
{
var marker = new google.maps.Marker({
position: coords,
map: map,
title: "You're here Bro!",
draggable: true,
animation: google.maps.Animation.DROP,
});
infoWindow.setPosition(coords);
infoWindow.setContent("You're here Bro!");
infoWindow.open(map , marker);
map.setCenter(coords);
}, function() {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
}
new AutocompleteDirectionsHandler(map);
}
这是初始化函数,我需要第二次变量coords
AutocompleteDirectionsHandler.prototype.route = function() {
if (!this.destinationPlaceId) {
return;
}
var me = this;
this.directionsService.route({
origin: coords,
destination: {'placeId': this.destinationPlaceId},
travelMode: this.travelMode
}, function(response, status) {
if (status === 'OK') {
me.directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
};
此代码无法将coords
变量传递给函数。第一个函数用于映射启动,第一个函数用于路由。
答案 0 :(得分:0)
您正尝试在不同的范围内访问“coords”变量。也许尝试在getCoords函数之外声明它,并将其设置在其中。 如下所示:
var coords = null;
function getCoords(position)
{
var longitude = position.coords.latitude;
var latitude = position.coords.longitude;
coords = new google.maps.LatLng(latitude, longitude);
alert(coords);
});
}