我正在使用他跟随js添加谷歌地图,它在foreach循环中从我的数据库中提取我的所有位置,我希望每个标记都有一个不同的图标,它将存储在一个字段中。
让我们说例如我有一个名为filename的字段,它将存储图像路径/名称(icon.jpg)。
我想知道如何调整由August Li编写的这个脚本来做到这一点。
<script type="text/javascript">
//Sample code written by August Li
var icon = new google.maps.MarkerImage("http://maps.google.com/mapfiles/ms/micons/blue.png",
new google.maps.Size(32, 32), new google.maps.Point(0, 0),
new google.maps.Point(16, 32));
var center = null;
var map = null;
var currentPopup;
var bounds = new google.maps.LatLngBounds();
function addMarker(lat, lng, info) {
var pt = new google.maps.LatLng(lat, lng);
bounds.extend(pt);
var marker = new google.maps.Marker({
position: pt,
icon: icon,
map: map
});
var popup = new google.maps.InfoWindow({
content: info,
maxWidth: 300
});
google.maps.event.addListener(marker, "click", function() {
if (currentPopup != null) {
currentPopup.close();
currentPopup = null;
}
popup.open(map, marker);
currentPopup = popup;
});
google.maps.event.addListener(popup, "closeclick", function() {
map.panTo(center);
currentPopup = null;
});
}
function initMap() {
map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(0, 0),
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR
},
navigationControl: true,
navigationControlOptions: {
style: google.maps.NavigationControlStyle.ZOOM_PAN
}
});
<?php
foreach ($dataProvider->models as $model) {
echo "addMarker({$model->lat}, {$model->lon}, '<b>$model->name</b><br />$model->website');";
}
?>
center = bounds.getCenter();
map.fitBounds(bounds);
}
</script>
答案 0 :(得分:2)
您只需要一个类似的功能:
function makeIcon(filename) {
return new google.maps.MarkerImage(
"http://example.com/path/to/icons/" + filename,
new google.maps.Size(32, 32), new google.maps.Point(0, 0),
new google.maps.Point(16, 32)
);
}
当然更新了图标文件位置的路径。
然后您需要更新addMarker函数以接受图标参数:
function addMarker(lat, lng, gicon, info) {
var pt = new google.maps.LatLng(lat, lng);
bounds.extend(pt);
var marker = new google.maps.Marker({
position: pt,
icon: gicon,
map: map
});
...
然后在PHP循环中,您需要单独添加makeIcon()调用。所以,例如,
<?php
foreach ($dataProvider->models as $model) {
echo "gicon = makeIcon(your filename);";
echo "addMarker({$model->lat}, {$model->lon}, gicon, '<b>$model->name</b><br />$model->website');";
}
?>
这回复了根据您的文件名获取gIcon对象的代码,然后将其传递给修改后的addMarker。