我有一个包含地址的数据库。我希望在谷歌地图上显示这些地址。我成功生成了像这样的json文件
$json = "https://maps.googleapis.com/maps/api/geocode/json?address=" . $row["HUISNUMMER"] . "+" . $row["STRAATNAAM"] . "+" . $row["STAD"] . "&key=MYPRIVATEKEY";
我可以像这样通过php获取lat和long(在我显示数据库记录的同一循环中):
$jsonzip = file_get_contents($json);
$jsondata = json_decode($jsonzip,true);
$jsonlat = $jsondata['results']['0']['geometry']['location']['lat'];
$jsonlong = $jsondata['results']['0']['geometry']['location']['lng'];
现在我被困在把它们变成标记。 现在我有默认的谷歌代码来显示标记
<script>
function initMap() {
var myLatLng = {lat: 50.6847204, lng: 4.1045525};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 8,
center: myLatLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: 'Hello World!'
});
}
</script>
如何在地图上添加所有位置?
答案 0 :(得分:1)
首先需要将PHP变量放入javascript中,例如:
<?php echo json_encode($jsondata); ?>
然后是一个for循环,其中包含一个标记的创建者。类似的东西:
for(var i = 0; i < jsondata.length; i++){
var marker = new google.maps.Marker({
position: jsondata[i]['geometry']['location']['lat'],
map: map,
title: 'Hello World!'
});
}
答案 1 :(得分:-1)
尝试
$locations = json_decode($jsonzip, true);
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position : new google.maps.LatLng(locations[i]['geometry']['location']['lat'], locations[i]['geometry']['location']['lng']),
map : map,
animation : google.maps.Animation.DROP,
icon : new google.maps.MarkerImage( '/PATH/marker.svg', null, null, null, new google.maps.Size(24, 24) ),
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent('<h3>TITLE</h3>');
infowindow.open(map, marker);
}
})(marker, i));
}