javascript Google Maps API (v3) 添加/更新标记
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10487003/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Google Maps API (v3) adding/updating markers
提问by Joseph Duffy
EDIT: It now works, but does not load if the user does not allow or have location-based services. See accepted answer comment for jsfiddle example.
编辑:它现在可以工作,但如果用户不允许或具有基于位置的服务,则不会加载。请参阅 jsfiddle 示例的已接受答案评论。
I've looked through a few tutorials and questions but I can't quiet understand what's happening (or in this case, not happening). I'm loading my map when the user clicks a link. This loads the map with the users current location in the center, and a marker at the users location. However, any markers outside of the if (navigation.location)
don't seem to load. Below is my current code:
我浏览了一些教程和问题,但我无法安静地理解发生了什么(或者在这种情况下,没有发生)。当用户单击链接时,我正在加载我的地图。这将加载以用户当前位置为中心的地图,以及用户位置处的标记。但是,外部的任何标记if (navigation.location)
似乎都没有加载。以下是我目前的代码:
function initialize() {
// Check if user support geo-location
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var point = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var userLat = position.coords.latitude;
var userLong = position.coords.longitude;
var mapOptions = {
zoom: 8,
center: point,
mapTypeId: google.maps.MapTypeId.HYBRID
}
// Initialize the Google Maps API v3
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
// Place a marker
new google.maps.Marker({
position: point,
map: map,
title: 'Your GPS Location'
});
});
} else {
var userLat = 53;
var userLong = 0;
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(userLat, userLong),
mapTypeId: google.maps.MapTypeId.HYBRID
}
// Place a marker
new google.maps.Marker({
position: point,
map: map,
title: 'Default Location'
});
// Initialize the Google Maps API v3
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
}
<?
for ($i = 0; $i < sizeof($userLocations); $i++) {
?>
var userLatLong = new google.maps.LatLng(<? echo $userLocations[$i]['lat']; ?>, <? echo $userLocations[$i]['long']; ?>);
new google.maps.Marker({
position: userLatLong,
map: map,
title:"<? echo $userLocations[$i]['displayName'] . ', ' . $userLocations[$i]['usertype']; ?>"
});
<?
}
?>
}
function loadMapScript() {
if (typeof(loaded) == "undefined") {
$("#showMap").css("display", "none");
$("#showMapLink").removeAttr("href");
$("#map").css("height", "600px");
$("#map").css("width", "600px");
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://maps.googleapis.com/maps/api/js?key=MY_API_KEY&sensor=true&callback=initialize";
document.body.appendChild(script);
loaded = true;
} else {
alert("Map already loaded!");
}
}
loadMapScript() is called when the user clicks a link. The php for loop loops through a pre-created array with all the information.
I'm guessing I don't fully understand it, as when if I put:
当用户单击链接时调用 loadMapScript()。php for 循环遍历一个包含所有信息的预先创建的数组。
我猜我没有完全理解它,好像我把:
var userLatLong = new google.maps.LatLng(53, 0);
new google.maps.Marker({
position: userLatLong,
map: map,
title:"Title"
});
into the console (Google Chrome), I get the error:
进入控制台(谷歌浏览器),我收到错误:
Error: Invalid value for property <map>: [object HTMLDivElement]
I don't, however, get any errors otherwise. Any help would be much appreciated! :)
但是,否则我不会收到任何错误。任何帮助将非常感激!:)
回答by benastan
navigator.geolocation.getCurrentPosition()
is asynchronous.
navigator.geolocation.getCurrentPosition()
是异步的。
Reorganize your code like this:
像这样重新组织你的代码:
var mapOptions = {
zoom: 8,
mapTypeId: google.maps.MapTypeId.HYBRID
}
function initialize() {
// Check if user support geo-location
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
makeMap(position.coords.latitude, position.coords.longitude, 'Your GPS Location');
});
} else {
makeMap(53, 0, 'DefaultLocation');
}
}
function makeMap(lat, lng, text) {
var point = new google.maps.LatLng(lat, lng);
mapOptions.center = point;
map = new google.maps.Map(document.getElementById("map"), mapOptions);
new google.maps.Marker({
position: point,
map: map,
title: text
});
<?php for ($i = 0; $i < sizeof($userLocations); $i++): ?>
var userLatLong = new google.maps.LatLng(<? echo $userLocations[$i]['lat']; ?>, <? echo $userLocations[$i]['long']; ?>);
new google.maps.Marker({
position: userLatLong,
map: map,
title:"<? echo $userLocations[$i]['displayName'] . ', ' . $userLocations[$i]['usertype']; ?>"
});
<?php endforeach ?>
}
Also, consider bootstraping the $userLocations into a JavaScript variable like this:
另外,考虑将 $userLocations 引导到一个 JavaScript 变量中,如下所示:
var userLocations = <?php print json_encode($userLocations) ?>;
Then execute your for loop in JavaScript, instead of mixing languages.
然后在 JavaScript 中执行你的 for 循环,而不是混合语言。
回答by Sean Mickey
Have you tried:
你有没有尝试过:
var map = null;
function initialize() { ... }
and then changing the code inside:
然后更改里面的代码:
map = new google.maps.Map( ... ); //make this the first line
if (navigator.geolocation) {
// Change the code from:
var map ...
// to:
map ...
You just reference the map directly (without the var
) everywhere else, so that should work.
您只需var
在其他任何地方直接引用地图(没有),这样就可以了。
回答by benastan
Change:
改变:
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
To:
到:
map = new google.maps.Map(document.getElementById("map"), mapOptions);
Because of var
, your map variable is tied the the scope of initialize()
. Removing it will set it as the global map variable (or window.map
), making it available outside of the initialize()
function.
因为var
,您的地图变量绑定了 的范围initialize()
。删除它会将其设置为全局映射变量(或window.map
),使其在initialize()
函数之外可用。
What's happening is you have an HTML element <div id="map">
. In many browsers, global variables are created from html element ids, so map
equals document.getElementById('map')
.
发生的事情是你有一个 HTML 元素<div id="map">
。在许多浏览器中,全局变量是从 html 元素 ID 创建的,因此map
equals document.getElementById('map')
。
Edit:Actually, this only explains your problem in the Chrome console. You need to set map
before trying to attach markers to it, as you do within if (navigator.geolocation) {}
. This also explains why none of the user location markers are being placed. The code to place them runs beforeinitialize()
. Put this code either within initialize
or within its own function, and call that function from initialize
.
编辑:实际上,这只能解释您在 Chrome 控制台中的问题。您需要map
在尝试将标记附加到它之前进行设置,就像在if (navigator.geolocation) {}
. 这也解释了为什么没有放置任何用户位置标记。放置它们的代码在initialize()
. 将此代码initialize
放在其自己的函数内或内,并从initialize
.
回答by chris
It looks like you're creating the marker, but not doing anything with it. Try changing your new Marker to look like this:
看起来您正在创建标记,但没有对其进行任何操作。尝试将您的新标记更改为如下所示:
var marker = new google.maps.Marker({
position: point, // this won't actually work - point is out of scope
title: 'Your GPS Location'
});
marker.setMap(map);
Edit: Make sure the point is inside the map!
编辑:确保该点在地图内!
var bounds = new google.maps.LatLngBounds();
bounds.extend(point);
map.fitBounds(bounds);