简体   繁体   English

转换 json 数组以用作谷歌地图标记

[英]Transform json Array to use as a google map marker

I am newbie and working my way so happy to get all the ideas I can.我是新手,我很高兴能得到我能想到的所有想法。 I have an external system which sends me this json file我有一个外部系统向我发送这个 json 文件

[149.9900000,-33.8900000,\\"Hume Hwy, Table Top\\"],[151.5400000,-33.0400000,\\"Newport Rd, Dora Creek\\"] [149.9900000,-33.8900000,\\"Hume Hwy, Table Top\\"],[151.5400000,-33.0400000,\\"Newport Rd, Dora Creek\\"]

I am not sure how I can convert this into a something like this我不确定如何将其转换为这样的

{"markers":[{"name":"Hume Hwy, Table Top","position":[149.9900000,-33.8900000],},{"name":"Newport Rd, Dora Creek","location":[151.5400000,-33.0400000]}}]}

so that I can consume into google maps.这样我就可以消费到谷歌地图中。

Cheers Nick干杯尼克

Considering your server sends proper JSON structure what you can do is parse the string to object using JSON.parse in browser by doing JSON.parse(response) .考虑到您的服务器发送正确的JSON结构,您可以做的是通过执行JSON.parse(response)在浏览器中使用JSON.parse将字符串解析为对象。

I am assuming your server sends;我假设您的服务器发送;

"[[149.99,-33.89,\\"Hume Hwy, Table Top\\"],[151.54,-33.04,\\"Newport Rd, Dora Creek\\"]]" which is a multidimensional proper json response. "[[149.99,-33.89,\\"Hume Hwy, Table Top\\"],[151.54,-33.04,\\"Newport Rd, Dora Creek\\"]]"这是一个多维正确的 json 响应。

We can parse this response and then map the response properly into your required object, so;我们可以解析此响应,然后将响应正确映射到您所需的对象中,因此;

  • Parse the response:解析响应:
const parsedMarkerData = JSON.parse("[[149.99,-33.89,\"Hume Hwy, Table Top\"],[151.54,-33.04,\"Newport Rd, Dora Creek\"]]");
  • Convert into your required structure:转换成你需要的结构:
const markers = [];
for(const marker of parsedMarkerData){
  // destructuring the array
  const [x, y, name] = marker;
  // putting into object
  markers.push({
    name, position: [x, y]
  });
}
  • Combining the response into the object with marker key:使用标记键将响应组合到对象中:
const finalObject = { markers };

Finally, finalObject contains the your required structure that can be consumed into google maps.最后, finalObject包含您需要的可以用于谷歌地图的结构。

Check this codesandbox to view all the parts running together.选中此代码和框以查看一起运行的所有部件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM