我有一个数据库,用于存储以前在Google地图上添加的标记的位置(纬度/经度)。我现在要做的是,创建一个将JSON对象作为参数的函数,包含那些标记位置并自动添加地图中的标记。我开始从我的数据库中获取标记并尝试循环JSON对象,如下所示:
{"markers":"\"[{\\\"k\\\":48.80686346108517,\\\"B\\\":1.494140625},{\\\"k\\\":50.28933925329177,\\\"B\\\":14.326171875},{\\\"k\\\":43.70759350405294,\\\"B\\\":21.357421875},{\\\"k\\\":30.977609093348686,\\\"B\\\":11.337890625},{\\\"k\\\":40.58058466412761,\\\"B\\\":-0.87890625},{\\\"k\\\":48.45835188280866,\\\"B\\\":1.318359375}]\""}
以下是我的代码的当前状态:
//Create a new set of markers based on received position.
function createMarkerBasedOnFetchedPosition(fetchedMarkersPosition)
{
var jsonData = JSON.parse(fetchedMarkersPosition);
alert(fetchedMarkersPosition);
map.addMarker({
lat: ? //Fetched from the JSON object parsing.
lng: ? //Fetched from the JSON object parsing.
animation: google.maps.Animation.DROP
});
任何人都可以帮我构建这个,我还不知道如何处理JSON对象来检索纬度/经度。我只是在寻找JavaScript解决方案。谢谢你的帮助!
答案 0 :(得分:1)
从当前代码开始,您需要使用for循环遍历标记,并向地图添加标记:
var data = '{"markers":[{"k":48.80686346108517,"B":1.494140625},{"k":50.28933925329177,"B":14.326171875},{"k":43.70759350405294,"B":21.357421875},{"k":30.977609093348686,"B":11.337890625},{"k":40.58058466412761,"B":-0.87890625},{"k":48.45835188280866,"B":1.318359375}]}';
function createMarkerBasedOnFetchedPosition(fetchedMarkersPosition)
{
var jsonData = JSON.parse(fetchedMarkersPosition);
for (var i = 0; i < jsonData.markers.length; i++) {
map.addMarker({
lat: jsonData.markers[i].k,
lng: jsonData.markers[i].b,
animation: google.maps.Animation.DROP
});
}
}
createMarkerBasedOnFetchedPosition(data);