【发布时间】:2017-04-26 01:19:15
【问题描述】:
我之前发布过,但我想更新问题,我试图删除另一个问题,但我不得不标记它,所以我不理会它。 我有 Google Map API 的密钥,但地图不会显示或加载。 这是我的代码:
Index.html
<script src = "loc.js"></script>
<input type ="button" value="Get Location" onclick="getLocation();">
<div id="spot"></div>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDEiqN2L1odkK645Il8bBVCDqatth6aZyU&callback=getLocation"></script>
<div id="map" style="width:100%;height:400px;"></div>
loc.js
function getLocation() {
var userSpot = document.getElementById("spot");
var map = document.getElementById("map");
//Using navigator, retrieves the users current location (works better with mobile phones)
if (navigator.geolocation) { //If the user says no (this prompts the user if they want their location known)
//then it'll go ahead and retrieve their location, if not prompts error message.
navigator.geolocation.getCurrentPosition(showLocation);
var currPosLat = position.coords.latitude;
var currPosLng = position.coords.longitude;
var mapOptions = {
center: new google.maps.LatLng(currPosLat, currPosLng),
zoom:12,
};
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
} else {
userSpot.innerHTML = "Geolocation is not supported by this browser type.";
}
}
function showLocation(position) {
var userSpot = document.getElementById("spot");
//Retrieves latitude and longitude using this second function called in the first
userSpot.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
【问题讨论】:
-
强调一下,主要问题在于 div id = map 应该在哪里,以及 loc.js 中的 getLocation 方法。这就是我的问题的根源。
标签: javascript google-maps google-maps-api-3 geolocation