我收到错误 Assertion failed: InvalidValueError: setMap: not an instance of Map;而不是谷歌地图网页上 StreetViewPanorama
的实例。然后我读了this question Stack Overflow 上的其他地方告诉我我需要一个 google.maps.MAP
对象的实例。我认为通过调用该对象来初始化我将调用该对象的 map 。
以前,我收到错误 i is not defined
所以我将 createMarker
函数移动到 $.getJSON
函数中,它有本地范围。
我需要在其他地方调用 google.mapsMap
吗?
我做错了什么?
HTML:
<body>
<h1 style="text-align: center;">Hello World</h1>
<div id="map"></div>
<ul id="list"></ul>
</body>
CSS:
#map {
height: 300px;
width: 600px;
border: 1px solid black;
margin: 0 auto;
}
JavaScript:
function initialize(){
var mapProp = {
center: new google.maps.LatLng(38, -78),
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map'), mapProp);
};
$(document).ready(function(){
var url = 'https://opendata.howardcountymd.gov/resource/96q9-qbh7.json';
initialize();
$.getJSON(url, function (data){
$.each(data, function(i, field) {
$('#list').append("<li>" + data[i].location.longitude + " & " + data[i].location.latitude + "</li>");
createMarker(data);
function createMarker (data) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(data[i].location.latitude, data[i].location.longitude),
map: map,
title: field.crossroad
});
};
});
});
});
最佳答案
作为 google.maps.Map
实例的 map 变量是 initialize
函数的本地变量。 createMarker
函数中的 map 变量未定义。一种选择:在全局范围内定义变量:
var map;
然后在initialize
函数中初始化它:
function initialize(){
var mapProp = {
center: new google.maps.LatLng(38, -78),
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map'), mapProp);
};
代码片段:
var map;
function initialize() {
var mapProp = {
center: new google.maps.LatLng(38, -78),
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map'), mapProp);
};
$(document).ready(function() {
var url = 'https://opendata.howardcountymd.gov/resource/96q9-qbh7.json';
initialize();
$.getJSON(url, function(data) {
$.each(data, function(i, field) {
$('#list').append("<li>" + data[i].location.longitude + " & " + data[i].location.latitude + "</li>");
createMarker(data);
function createMarker(data) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(data[i].location.latitude, data[i].location.longitude),
map: map,
title: field.crossroad
});
};
});
});
});
#map {
height: 300px;
width: 600px;
border: 1px solid black;
margin: 0 auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<h1 style="text-align: center;">Hello World</h1>
<div id="map"></div>
<ul id="list"></ul>
Another option would be to return the map
from the initialize function
关于javascript - 为什么这不是 google.maps.Map 的 map 实例?无效值错误 : setMap: not an instance of Map;,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33641663/