我正在尝试将自定义图标添加到Google地图中。但是,当我添加创建自定义图标的代码时,自定义图标不会加载到地图上。知道为什么吗?一个简单的方法来纠正这个问题?
这是我的代码示例
function initMap() {
// specify where the map is centered
var myLatLng = {lat: 37.77493, lng: -122.419416};
var map = new google.maps.Map(document.getElementById('map'), {
center: myLatLng,
zoom: 12
});
$.get("/data", function( data ) {
console.log(data);
placeMarkers(data, map);
});
}
// Create a marker
function placeMarkers(data, map){
var icon = {
url:'http://www.arclightbrewing.com/files/Food%20Truck%20Court.png',
size: new google.maps.Size(20, 32),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(0, 0)
};
var shape = {
coord: [16, 0, 0, 16, 16, 45, 32 , 16],
type: 'poly'
};
var locations = data["locations"];
for (i = 0; i < locations.length; i++) {
var loc = locations[i]
, lat = loc["latitude"]
, lng = loc["longitude"];
if (lat && lng){
var marker = new google.maps.Marker({
position: {lat:parseFloat(lat), lng:parseFloat(lng)},
map:map,
icon:icon,
shape:shape
});
}
}
}`
答案 0 :(得分:0)
您的图标定义不正确。这对我有用:
var icon = {
url: 'http://www.arclightbrewing.com/files/Food%20Truck%20Court.png',
size: new google.maps.Size(488,349), // original image size
scaledSize: new google.maps.Size(64, 40), // desired image size
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(32, 40)
};
scaledSize |类型:尺寸
缩放后整个图像的大小(如果有)。使用此属性可以拉伸/缩小图像或精灵。
(你不需要告诉它实际的大小,尽管你可以)
代码段
var map;
function initMap() {
// specify where the map is centered
var myLatLng = {
lat: 37.77493,
lng: -122.419416
};
map = new google.maps.Map(document.getElementById('map'), {
center: myLatLng,
zoom: 12
});
// $.get("/data", function(data) {
console.log(data);
placeMarkers(data, map);
// });
}
// Create a marker
function placeMarkers(data, map) {
var icon = {
url: 'http://www.arclightbrewing.com/files/Food%20Truck%20Court.png',
scaledSize: new google.maps.Size(64, 40),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(32, 40)
};
var shape = {
coord: [16, 0, 0, 16, 16, 45, 32, 16],
type: 'poly'
};
var locations = data["locations"];
for (i = 0; i < locations.length; i++) {
var loc = locations[i],
lat = loc["latitude"],
lng = loc["longitude"];
if (lat && lng) {
var marker = new google.maps.Marker({
position: {
lat: parseFloat(lat),
lng: parseFloat(lng)
},
map: map,
icon: icon,
shape: shape
});
}
}
}
google.maps.event.addDomListener(window, "load", initMap);
var data = {
locations: [{
latitude: 37.7598648,
longitude: -122.4147977,
name: "Mission District, San Francisco, CA, USA"
}, {
latitude: 37.7591221,
longitude: -122.3895378,
name: "Dogpatch, San Francisco, CA, USA"
}]
};
&#13;
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
&#13;
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map"></div>
&#13;