我正在使用Google Maps API v3制作网站。 将标记添加到地图中,并从标记数据中获取属性
标记数据集
var markerData = [
"lat": '21.0236081',
"long": '105.789596',
"icon": 'http://i.imgur.com/0Js6A7w.gif',
"description": 'blah blah'
];
将标记固定到地图上
for (var i = 0; i < markerData.length; i++) {
var data = markerData[i];
var myLatLng = new google.maps.LatLng(data.lat, data.long);
var image = "'" + data.icon + "'";
var marker = new google.maps.Marker({
position: myLatLng,
icon: image
});
(function (marker, data) {
google.maps.event.addListener(marker, "click", function (e) {
infoWindow.setContent(data.description);
infoWindow.open(map, marker);
});
})(marker, data);
markerList.push(marker);
}
我无法获得放入标记的“图标”属性的链接。 有人可以给我一些建议吗?
谢谢大家!!
答案 0 :(得分:1)
您的代码中有许多拼写错误:
lat
和long
属性应该是数字:var markerData = [{
"lat": 21.0236081,
"long": 105.789596,
"icon": "http://maps.google.com/mapfiles/ms/micons/blue.png", // 'http://i.imgur.com/0Js6A7w.gif',
"description": 'blah blah'
}];
map
属性设置为map
对象:var marker = new google.maps.Marker({
position: myLatLng,
icon: image,
map: map
});
var image = "'" + data.icon + "'";
应该是:
var image = data.icon;
(data.icon
已经是一个字符串)
代码段
var geocoder;
var map;
var markerList = [];
function initialize() {
var map = new google.maps.Map(
document.getElementById("map_canvas"), {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var markerData = [{
"lat": 21.0236081,
"long": 105.789596,
"icon": "http://maps.google.com/mapfiles/ms/micons/blue.png", // 'http://i.imgur.com/0Js6A7w.gif',
"description": 'blah blah'
}];
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < markerData.length; i++) {
var data = markerData[i];
var myLatLng = new google.maps.LatLng(data.lat, data.long);
var image = data.icon;
var marker = new google.maps.Marker({
position: myLatLng,
icon: image,
map: map
});
(function(marker, data) {
google.maps.event.addListener(marker, "click", function(e) {
infoWindow.setContent(data.description);
infoWindow.open(map, marker);
});
})(marker, data);
markerList.push(marker);
bounds.extend(myLatLng);
if (markerList.length > 1) map.fitBounds(bounds)
else map.setCenter(myLatLng);
}
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map_canvas"></div>
答案 1 :(得分:0)
您必须将地图对象传递给标记
var marker = new google.maps.Marker({ // put a marker on map
position: {lat:lat, lng:lng},
map: map,
icon: iconURL
}