[英]I'm trying to add a marker using Google Maps Javascript API but it isn't working
This is my Javascript code to obtain the marker. 这是我获取标记的Javascript代码。 The page is loading the map but the marker doesn't appear.
页面正在加载地图,但标记未显示。
function initMap(){
var options = {
zoom:13,
center:{lat:42.3601,lng:-71.0589}//Change these coordinates to change the center
}
var map = new google.maps.Map(document.getElementById('map'),options);
}
var location = new google.maps.LatLng(42.3601, -71.0589);
var marker = new google.maps.Marker({
position:location,
map:this
});
marker.setMap(map);
Two issues: 两个问题:
create the marker
inside your initMap
function (which most likely is the callback function that runs once the API is loaded) 在
initMap
函数中创建marker
(很可能是加载API后运行的回调函数)
use a valid value for the google.maps.Map
object. 使用
google.maps.Map
对象的有效值。 (the map
variable inside the initMap
function would be best, this
where you have it is probably the window
object). (在
map
里面变量initMap
功能将是最好的, this
,你有这大概是window
对象)。
function initMap(){
var options = {
zoom:13,
center:{lat:42.3601,lng:-71.0589}//Change these coordinates to change the center
}
var map = new google.maps.Map(document.getElementById('map'),options);
var location = new google.maps.LatLng(42.3601, -71.0589);
var marker = new google.maps.Marker({
position:location,
map:map
});
}
proof of concept fiddle 概念证明小提琴
code snippet: 代码段:
function initMap() { var options = { zoom: 13, center: { lat: 42.3601, lng: -71.0589 } //Change these coordinates to change the center } var map = new google.maps.Map(document.getElementById('map'), options); var location = new google.maps.LatLng(42.3601, -71.0589); var marker = new google.maps.Marker({ position: location, map: map }); }
html, body, #map { height: 100%; margin: 0; padding: 0; }
<div id="map"></div> <!-- Replace the value of the key parameter with your own API key. --> <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap" async defer></script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.