我对API很陌生,我一直试图通过获取我的位置并将其传递给新的google.maps.Map来运行它,但它没有显示地图。我想我已经犯了一些错误但是javascript中的控制台没有显示任何错误。请仔细看看我的代码,看看我应该做些什么。先感谢您。
var map;
function displayLocation(position){
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
var pLocation = document.getElementById("location");
pLocation.innerHTML = latitude + ", " + longitude;
showMap(position.coords);
}
function showMap (coords){
var googleLatLong = {lat: coords.latitude, lng: coords.longitude};
console.log(googleLatLong);
var mapOptions = {
zoom: 11,
center: googleLatLong,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var mapDiv = document.getElementById("map");
map = new google.maps.Map(mapDiv, mapOptions);
console.log(map);
}
function displayError(error){
var errors = ["Unknow error", "Permission denied by user", "Position not available", "Timeout error"];
var message = errors[error.code];
console.warn("Error in getting your location: " + message, error.message);
}
window.onload = function(){
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(displayLocation, displayError);
} else {
alert("Error Occor!");
}
}
<!DOCTYPE html>
<html>
<head>
<style>
body{
background-color: #fafafa;
font-family: Helvetica, Arial, sans-serif;
margin: 20px;
}
div #map{
width: 600px;
height: 400px;
}
</style>
</head>
<body>
<h3>Find nearby places</h3>
<p id="location"></p>
<div id="map">Loading...</div>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=MyKey">
</script>
<script src="script.js"></script>
</body>
</html>
答案 0 :(得分:0)
替换MyKey
src="https://maps.googleapis.com/maps/api/js?key=MyKey">
关键的google api