我正在使用jquery谷歌地图插件。这是我的代码
$( document ).ready(function() {
var locations = [];
locations.push([{
'position': '57.7973333,12.0502107',
'bounds': true
}, 'Hello World!']);
$('#map_canvas').gmap().bind('init', function(ev, map) {
for (var i=0; i<locations.length; i+=1) {
var loc = locations[i];
/*
$('#map_canvas').gmap('addMarker', loc[0]).click(function() {
$('#map_canvas').gmap('openInfoWindow', {'content': loc[1]}, this);
});
*/
}
$('#map_canvas').gmap('option', 'zoom', 10);
if ( navigator.geolocation ) {
function success(pos) {
// Location found, show map with these coordinates
//drawMap(new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude));
$('#map_canvas').gmap({
'center': new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude)
});
//alert(pos.coords.latitude);
//alert(pos.coords.longitude);
//$('#map_canvas').gmap({ 'center': '42.345573,-71.098326' });
}
function fail(error) {
$('#map_canvas').gmap({ 'center': '42.345573,-71.098326' });
}
// Find the users current position. Cache the location for 5 minutes, timeout after 6 seconds
navigator.geolocation.getCurrentPosition(success, fail, {maximumAge: 500000, enableHighAccuracy:true, timeout: 6000});
} else {
$('#map_canvas').gmap({ 'center': '42.345573,-71.098326' });
}
});
});
问题在于,我想将位置(而不是标记)设置为用户所在的位置,但问题是代码不会移动位置。它将其保持在默认的纬度/经度0,0。我不知道出了什么问题。我在成功函数中添加了一个警告声明,它会发出警报..
有谁知道最近发生了什么?
谢谢
答案 0 :(得分:1)
Javascript经常使用异步进程。这意味着:您(脚本编写者)发送请求,并附带回调。 Javascript需要花费时间,只要它准备就绪,它就会调用该回调。
与此同时,它继续使用脚本的其余部分;它不会等待。
geolocation是其中一种异步服务。您发送请求,脚本的其余部分继续;如果地理位置找到位置,则只有这样才能使用该功能。
这意味着你总是需要一个默认值;你总是需要为地理定位失败时编写默认代码。
以下是一个例子:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>jquery google maps not able to set location</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=true"></script>
<script src="http://jquery-ui-map.googlecode.com/svn/trunk/ui/jquery.ui.map.js"></script>
<script>
function initialize() {
// we send a request to get the position of the client.
// This can take some time, so we don't wait.
// We create the map and set a default location.
// If and when geolocation found the client's location, we change the center of the map
// else, we don't
// new map, with default location
$('#map_canvas').gmap({
center: '42.345573,-71.098326',
zoom: 10
});
if ( navigator.geolocation ) {
function success(pos) {
// set the center
$('#map_canvas').gmap('option', 'center', new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude));
}
function fail(error) {
// maybe you want to do something here
}
// start of the request to get the client's position
navigator.geolocation.getCurrentPosition(success, fail, {maximumAge: 500000, enableHighAccuracy:true, timeout: 6000});
}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<style>
#map_canvas {
height: 500px;
}
</style>
</head>
<body>
<div id="map_canvas"></div>
</body>
</html>