我的后续页面使用Google Maps API显示Google地图
<!DOCTYPE HTML>
<html>
<head>
<style type="text/css">
#map{
width:400px;
height:400px;
border:2px solid black;
margin-top:20px;
}
</style>
</head>
<body>
<div id="location">
<p>Your location will be displayed here</p>
</div>
<div id="map"></div>
<script>
var map;
var div = document.getElementById("location");
window.onload = getMyLocation;
function getMyLocation(){
if(navigator.geolocation){
navigator.geolocation.getCurrentPosition(displayLocation,displayError);
}else{
alert("Sorry, your browser does not support geolocation");
}
}
function displayLocation(position){
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
div.innerHTML = "You are at Latitude: "+latitude+", Longitude: "+longitude;
showMap(position.coords);
}
function displayError(error){
if(error.code==0){
div.innerHTML="An unknown error occurred.";
}else if(error.code==1){
div.innerHTML="You denied the request for Geolocation.";
}else if(error.code==2){
div.innerHTML="Location information is unavailable.";
}else if(error.code==3){
div.innerHTML="The request to get user location timed out.";
}
}
function showMap(coords){
var googleLatAndLong = new google.maps.LatLng(coords.latitude,coords.longitude);
var mapOptions = {
zoom:10,
center:googleLatAndLong,
maptypeId:google.maps.MapTypeId.ROADMAP
};
var mapDiv=document.getElementById("map");
map = new google.maps.Map(mapDiv,mapOptions);
var title="Your location";
var content = "You are here: "+coords.latitude+", "+coords.longitude;
addMarker(map,googleLatAndLong,title,console);
}
function addMarker(map,latlong,title,content){
var markerOptions = {
position:latlong,
map:map,
title:title,
clickable:true
};
var marker = new google.maps.Marker(markerOptions);
var infoWindowOptions = {
content:content,
position:latlong
};
var infoWindow = new google.maps.InfoWindow(infoWindowOptions);
google.maps.event.addListener(marker,"click",function(){
infoWindow.open(map);
});
}
</script>
<script src="https://maps.google.com/maps/api/js?sensor=true"></script>
</body>
</html>
注意:代码段可能无效,因为SO阻止了Geolocation API的请求。
当我加载页面时,地图会正确显示标记,但是当我点击标记时没有任何反应(它应该显示一个窗口)并且JS控制台会抛出以下错误
Uncaught InvalidValueError:setContent:not a string;和[对象控制台]
我阅读了类似的帖子,似乎问题在于,无论Content有什么价值,它都不是字符串。唯一的内容变量在这里声明
var content = "You are here: "+coords.latitude+", "+coords.longitude;
addMarker(map,googleLatAndLong,title,console);
}
function addMarker(map,latlong,title,content){
var markerOptions = {
position:latlong,
map:map,
title:title,
clickable:true
};
var marker = new google.maps.Marker(markerOptions);
var infoWindowOptions = {
content:content,
我尝试将coords.latitude和coords.longitude转换为字符串(不在此版本的代码中)并且它没有任何区别。
关于导致这种情况的任何想法?代码来自Head First HTML5编程,他们根本没有提到这个问题。
答案 0 :(得分:3)
这是语法错误
我有
addMarker(地图,googleLatAndLong,标题,控制台);
应该是
addMarker(地图,googleLatAndLong,标题,内容);
不确定我从哪里获得'控制台'。