【发布时间】:2020-05-16 05:28:04
【问题描述】:
function showPosition() {
navigator.geolocation.getCurrentPosition(showMap, error);
}
function showMap(position) {
// Get location data
var mylatlong = position.coords.latitude + "," + position.coords.longitude;
// Set Google map source url
var mapLink = "https://maps.googleapis.com/maps/api/staticmap?center=" + mylatlong + "&size=50x50";
// Create and insert Google map
document.getElementById("embedMap").innerHTML = "<img alt='Map Holder' src='" + mapLink + "'>";
}
function error(err) {
console.warn(`ERROR(${err.code}): ${err.message}`);
}
<input type="button" value="Add Map" onclick="showPosition()" />
<div id="embedMap">
<!--Google map will be embedded here-->
</div>
我是 Javascript 和 HTML 的新手,目前正在测试如何在单击按钮后获取当前位置并在谷歌地图中显示它。我已经尝试过了,但我仍然无法在地图中获取我当前的位置。
app.js
function showPosition() {
navigator.geolocation.getCurrentPosition(showMap);
}
function showMap(position) {
// Get location data
var latlong = position.coords.latitude + "," + position.coords.longitude;
// Set Google map source url
var mapLink = "https://maps.googleapis.com/maps/api/staticmap?center="+latlong+"&zoom=16&size=400x300&output=embed";
// Create and insert Google map
document.getElementById("embedMap").innerHTML = "<img alt='Google map' src='"+ mapLink +"'>";
}
index.html
<input type="button" value="Add Map" onclick="showPosition()"/>
<div id="embedMap">
<!--Google map will be embedded here-->
</div>
【问题讨论】:
-
问题可能是地理定位已在本文档中被功能策略禁用。在使用此代码之前检查Is there a way to check if geolocation has been DECLINED with Javascript?。
-
您好,我已经尝试检查地理位置是否被拒绝,但它没有显示任何内容,并且地图仍然无法正常工作。
-
我刚刚添加了sn-p。谢谢!
-
我已经更新了演示。您在单击按钮时遇到任何错误吗?
-
并非如此。我尝试以文本格式显示当前位置,我可以清楚地看到我的纬度和经度。我认为问题出在 mapLink 中。我还可以看到“谷歌地图”替代文字。只是地图没有显示。
标签: javascript html google-maps geolocation