【发布时间】:2018-07-10 03:21:00
【问题描述】:
这可能是一个非常基本的问题。我有代码工作,但它在逻辑上是错误的。
我需要找到地理位置并在那里设置地图中心。如果我无法访问地理位置,那么我想将中心设置在新天堂。我知道我应该使用回调,但我不知道如何。
现在代码可以工作,但速度很慢。它首先将中心设置为新天堂,然后跳转到真正的地理位置。我想马上去真正的。我应该如何做到这一点?
谢谢。
$(document).ready(function() {
let canvas = $("#map-canvas").get(0);
// Styles for map
// https://developers.google.com/maps/documentation/javascript/styling
let styles = [
// Hide Google's labels
{
featureType: "all",
elementType: "labels",
stylers: [
{visibility: "off"}
]
},
// Hide roads
{
featureType: "road",
elementType: "geometry",
stylers: [
{visibility: "off"}
]
}
];
// Options for map
// https://developers.google.com/maps/documentation/javascript/reference#MapOptions
let options = {
center: {lat: 41.3184, lng: -72.9318},//new heaven
disableDefaultUI: true,
mapTypeId: google.maps.MapTypeId.ROADMAP,
maxZoom: 14,
panControl: true,
styles: styles,
zoom: 13,
zoomControl: true
};
// Instantiate map
map = new google.maps.Map(canvas, options);
//reset center if geolocation is accessible (HERE IS THE PROBLEM)
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
map.setCenter(pos);
var marker = new google.maps.Marker({
position: map.getCenter(),
map:map,
label:"Around Me"
});
});
}
});
【问题讨论】:
标签: javascript jquery google-maps google-maps-api-3