Google Map无法显示且全局longitude、latitude取值为undefined问题求助
问题原因
navigator.geolocation.getCurrentPosition是异步API,回调函数只会在浏览器获取到用户定位权限、拿到定位结果之后才会执行。你写在它外部的alert(latitude)、地图初始化、标记创建逻辑,都会在定位结果返回前执行,此时全局的经纬度变量还未赋值,自然为undefined。- 你在定位回调内部用
var重新声明了同名的longitude和latitude变量,这两个是回调的局部变量,赋值不会同步到你最开头声明的全局变量上,相当于全局变量从头到尾都没有被赋值。 - 地图实例
map是在initMap函数内部才初始化的,你写在initMap外部的标记创建代码执行时,map还是undefined,标记无法挂载,地图也无法正常渲染。
修复后的代码
var map; var longitude; var latitude; navigator.geolocation.getCurrentPosition(function(position) { console.log("I'm at " + position.coords.latitude + ", " + position.coords.longitude); // 直接给全局变量赋值,不要加var重新声明 longitude = position.coords.longitude; latitude = position.coords.latitude; // 拿到定位后再初始化地图 initMap(); // 初始化当前位置标记 var marker_origin = new google.maps.Marker({ map: map, title: "you are here", icon: { scaledSize: { width: 50, height: 50 }, url: "http://maps.google.com/mapfiles/kml/paddle/blu-blank.png" }, position: { lat: parseFloat(latitude), lng: parseFloat(longitude) } }); // 初始化其他点位标记 {% for row in hubdb_table_rows(table_id) %} var marker_{{ row.hs_id }} = new google.maps.Marker({ map: map, position: {lat: {{ row.location["lat"] }}, lng: {{ row.location["lon"] }}}, title: '{{ row.name }}', icon: { scaledSize: { width: 40, height: 40 }, url: "http://maps.google.com/mapfiles/kml/shapes/dining.png" } }); marker_{{ row.hs_id }}.addListener('click', function() { new google.maps.InfoWindow({ content: '<div> {{ row.name }} is {{ row.location|geo_distance(request.query_dict['lat'], request.query_dict['lon'], "mi")|round(3) }} miles away</div>' }).open(map, marker_{{ row.hs_id }}); }); {% endfor %} }); function initMap() { map = new google.maps.Map(document.getElementById('map'), { center: { // 转成数字类型,避免字符串类型导致地图API报错 lat: parseFloat(latitude), lng: parseFloat(longitude) }, zoom: 8 }); }
额外注意点
- 经纬度的值需要转成数字类型再传给地图API,避免字符串格式导致API解析报错。
- 要确保用户授权定位权限,如果用户拒绝授权,你可以补充定位失败的回调逻辑,给一个默认的经纬度初始化地图。
内容的提问来源于stack exchange,提问作者baxi
相关产品推荐
相关产品推荐

