我的商店定位器设置为以用户当前位置为中心,但如果用户不允许知道他/她的位置,如何将其设为默认位置? else语句中的代码不起作用,但我不确定原因。这就是我所拥有的:
google.maps.event.addDomListener(window, 'load', function() {
(function() {
if(!!navigator.geolocation) {
var map;
var mapOptions = {
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
navigator.geolocation.getCurrentPosition(function(position) {
var geolocate = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
map.setCenter(geolocate);
});
} else {
var map = new google.maps.Map(document.getElementById('map-canvas'), {
center: new google.maps.LatLng(37.7749, -122.4194),
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
}
var panelDiv = document.getElementById('panel');
var data = new MedicareDataSource;
var view = new storeLocator.View(map, data, {
geolocation: false,
features: data.getFeatures()
});
new storeLocator.Panel(panelDiv, {
view: view
});
})();
});
答案 0 :(得分:0)
else中的代码不起作用,因为它永远不会被执行(!!navigator.geolocation
为真)。如果geolocation
可用,但遇到错误,则会调用error
函数,但您没有定义。
getCurrentPosition方法定义为(来自the documentation):
navigator.geolocation.getCurrentPosition(success [,error [,options]])
的参数强>
success - 一个回调函数,它将Position对象作为唯一的输入参数 错误 - 可选 - 一个可选的回调函数,它将PositionError对象作为其唯一的输入参数 选项 - 可选 - 可选的PositionOptions对象。
添加错误功能以设置地图的中心:
function error(err) {
console.log('ERROR('+err.code+'): '+err.message);
if (map && map.setCenter) map.setCenter(new google.maps.LatLng(37.7749, -122.4194))
};
然后将其添加到.getCurrentPosition
来电:
navigator.geolocation.getCurrentPosition(function(position) {
var geolocate = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
map.setCenter(geolocate);
}, error);
proof of concept fiddle (https: works)
proof of concept fiddle (http: fails due to non-secure origin)
代码段
var map;
function error(err) {
console.log('ERROR(' + err.code + '): ' + err.message);
if (map && map.setCenter) map.setCenter(new google.maps.LatLng(37.7749, -122.4194))
};
google.maps.event.addDomListener(window, 'load', function() {
if (!!navigator.geolocation) {
var mapOptions = {
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
navigator.geolocation.getCurrentPosition(function(position) {
var geolocate = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
map.setCenter(geolocate);
}, error);
} else {
map = new google.maps.Map(document.getElementById('map-canvas'), {
center: new google.maps.LatLng(37.7749, -122.4194),
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
}
});

html,
body,
#map-canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}

<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map-canvas"></div>
&#13;