我正在尝试创建一个颜色框链接,要求用户允许检测他的位置,如果用户同意他从他的位置获得一个方向的地图。 现在我设法让它工作但不是很好。在第一次用户需要给予权限时,地图加载完美,但是在第二次许可时已经给出地图未正确加载。
我的代码:
function directionMap() {
var position;
jQuery('.direction-map').colorbox({
maxWidth: '100%',
maxHeight: '100%',
opacity: 0.5,
html: '<div id="map" style="width: 800px; height: 500px"></div>',
onLoad: function() {
var success = function(pos) {
var lat = pos.coords.latitude,
long = pos.coords.longitude,
coords = {lat: lat, lng: long};
var start = coords;
var target = {lat: 31.273257, lng: 34.797528};
var map = new google.maps.Map(document.getElementById('map'), {
center: start,
scrollwheel: false,
zoom: 7
});
var directionsDisplay = new google.maps.DirectionsRenderer({
map: map
});
// Set destination, origin and travel mode.
var request = {
destination: target,
origin: start,
travelMode: google.maps.TravelMode.DRIVING
};
// Pass the directions request to the directions service.
var directionsService = new google.maps.DirectionsService();
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
// Display the route on the map.
directionsDisplay.setDirections(response);
}
});
}
var error = function() {
alert('Can\'t find your location');
}
if (geoPosition.init()) {
geoPosition.getCurrentPosition(success, error, {
enableHighAccuracy:true,
timeout: 1000
});
}
return false;
},
});
}
答案 0 :(得分:0)
我找到了解决方案。 问题是地图应该在颜色框完成后加载,但是只要给出了位置权限。所以我用“onclick”处理程序编写它并将colorbox加载到success变量中。 这是代码:
function directionMap() {
document.getElementById('get_location').onclick = function() {
var success = function(pos) {
jQuery('.direction-map').colorbox({
maxWidth: '100%',
maxHeight: '100%',
opacity: 0.5,
html: '<div id="map" style="width: 800px; height: 500px"></div>',
open: true,
onComplete: function() {
var lat = pos.coords.latitude,
long = pos.coords.longitude,
coords = {lat: lat, lng: long};
var start = coords;
var target = {lat: 31.273257, lng: 34.797528};
var map = new google.maps.Map(document.getElementById('map'), {
center: start,
scrollwheel: false,
zoom: 7
});
var directionsDisplay = new google.maps.DirectionsRenderer({
map: map
});
// Set destination, origin and travel mode.
var request = {
destination: target,
origin: start,
travelMode: google.maps.TravelMode.DRIVING
};
// Pass the directions request to the directions service.
var directionsService = new google.maps.DirectionsService();
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
// Display the route on the map.
directionsDisplay.setDirections(response);
}
});
}
});
}
var error = function() {
alert('Can\'t find your location');
}
if (geoPosition.init()) {
geoPosition.getCurrentPosition(success, error, {
enableHighAccuracy:true,
timeout: 1000
});
}
return false;
}
}