我已启动并运行 map ,但无法在“中心”和“位置”中指定的纬度和经度处放置标记。有人看到错误吗?我之前已经完成了这个工作,但是在添加样式数组之后,它停止了,我一定是不小心弄乱了一些东西,但我现在没有看到它。
<div id="map"></div>
<script src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script>
var map;
function initialize() {
var mapOptions = {
zoom: 17,
center: new google.maps.LatLng(36, -110),
mapTypeId: google.maps.MapTypeId.ROADMAP,
styles: styleArray,
scrollwheel: false,
};
map = new google.maps.Map(document.getElementById('map'),
mapOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
var styleArray = [
{
featureType: "all",
stylers: [ { saturation: -80 } ]
},
{
featureType: "road.arterial",
elementType: "geometry",
stylers: [ { hue: "#00ffee" }, { saturation: 50 } ]
},
{
featureType: "poi.business",
elementType: "labels",
stylers: [ { visibility: "off" } ]
}
];
var marker = new google.maps.Marker({
position: (36, -110),
title:"Hello World!",
map: (google.maps.MapTypeId.ROADMAP),
});
marker.setMap(google.maps.MapTypeId.ROADMAP);
</script>
最佳答案
发布的代码中存在 JavaScript 错误:
-
InvalidValueError: setPosition: not a LatLng or LatLngLiteral: not an Object
-
InvalidValueError: setMap: not an instance of Map; and not an instance of StreetViewPanorama
您的代码存在几个问题:
您的标记是在
initialize
之外实例化的。函数(因此它在定义map
变量之前实例化。将其移到initialize
函数内。marker.setMap
函数需要google.maps.Map
对象作为其参数,这是不正确的:marker.setMap(google.maps.MapTypeId.ROADMAP);
应该是:
marker.setMap(map);
这是不正确的,位置需要是
google.maps.LatLng
对象或google.maps.LatLngLiteral
,(36, -110)
两者都不是,并且map
属性(property)需要是google.maps.LatLng
;这个:var marker = new google.maps.Marker({ position: (36, -110), title:"Hello World!", map: (google.maps.MapTypeId.ROADMAP), });
应该是:
var marker = new google.maps.Marker({
position: google.maps.LatLng(36, -110),
title:"Hello World!",
map: map,
});
代码片段:
var map;
function initialize() {
var mapOptions = {
zoom: 17,
center: new google.maps.LatLng(36, -110),
mapTypeId: google.maps.MapTypeId.ROADMAP,
styles: styleArray,
scrollwheel: false,
};
map = new google.maps.Map(document.getElementById('map'),
mapOptions);
var marker = new google.maps.Marker({
position: new google.maps.LatLng(36, -110),
title: "Hello World!",
map: map,
});
marker.setMap(map);
}
google.maps.event.addDomListener(window, 'load', initialize);
var styleArray = [{
featureType: "all",
stylers: [{
saturation: -80
}]
}, {
featureType: "road.arterial",
elementType: "geometry",
stylers: [{
hue: "#00ffee"
}, {
saturation: 50
}]
}, {
featureType: "poi.business",
elementType: "labels",
stylers: [{
visibility: "off"
}]
}];
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map"></div>
关于javascript - Google Maps API,根本无法显示标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45291934/