通过JSON迭代以填充地图

发布于 2025-01-19 15:07:39 字数 2118 浏览 1 评论 0原文

我正在尝试通过JSON文件迭代并将相关数据放入我的标记变量中。通过每个迭代标记都应该改变,但是我被卡住了。有人知道该怎么做还是我怎么做?

这是我的json的较小版本:

{"properties": 
[{"latitude":"53.542637347578406","longitude":"-113.51709427725768",
"account":"1061985","value":"$500"},
{"latitude":"53.5384925504052","longitude":"-113.520385218556",
"account":"1248558","value":"$500"}]}

这是我的javascript代码:

function initMap() {
    map = new google.maps.Map(document.getElementById("map"), {
        mapId: "8e0a97af9386fef",
        center: {lat: 53.55204130841203, lng: -113.49684664653883},
        zoom: 11,
        mapTypeControl: false,
    });
    const markers = [
        [
            "Assessed",
            53.432556261744296,
            -113.61359034412152,
            "house-svgrepo-com.svg",
            40,
            41
        ]
    ];
    for (let i = 0; i < markers.length; i++) {
        const currMarker = markers[i];
        const marker = new google.maps.Marker({
            position: {lat: currMarker[1], lng: currMarker[2]},
            map,
            title: currMarker[0],
            icon: {
                url: currMarker[3],
                scaledSize: new google.maps.Size(currMarker[4], currMarker[5])

            },
//            animation: google.maps.Animation.DROP
        });
    }
}

我在这里尝试做的是填充const标记带有纬度,经度,并评估JSON的价值。 因此:“评估”将变成json“值”

这是HTML文件:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Edmonton Property Assessments</title>
    <link rel="stylesheet" href="style.css">
  </head>
  <body>
      <h1>Map View</h1>
      <div id="map"></div>
      <script src="script.js"></script>
      <script
          async
          src="https://maps.googleapis.com/maps/api/js?key=UR_KEY&callback=initMap">   
      </script>
  </body>
</html>

I am trying to iterate through a JSON file and put relevant data inside my markers variable. through each iteration markers should change, however I am stuck. Does anyone know how to do this or how I could?

This is a smaller version of my JSON:

{"properties": 
[{"latitude":"53.542637347578406","longitude":"-113.51709427725768",
"account":"1061985","value":"$500"},
{"latitude":"53.5384925504052","longitude":"-113.520385218556",
"account":"1248558","value":"$500"}]}

This is my JavaScript Code:

function initMap() {
    map = new google.maps.Map(document.getElementById("map"), {
        mapId: "8e0a97af9386fef",
        center: {lat: 53.55204130841203, lng: -113.49684664653883},
        zoom: 11,
        mapTypeControl: false,
    });
    const markers = [
        [
            "Assessed",
            53.432556261744296,
            -113.61359034412152,
            "house-svgrepo-com.svg",
            40,
            41
        ]
    ];
    for (let i = 0; i < markers.length; i++) {
        const currMarker = markers[i];
        const marker = new google.maps.Marker({
            position: {lat: currMarker[1], lng: currMarker[2]},
            map,
            title: currMarker[0],
            icon: {
                url: currMarker[3],
                scaledSize: new google.maps.Size(currMarker[4], currMarker[5])

            },
//            animation: google.maps.Animation.DROP
        });
    }
}

What im trying to do here is populate const markers with latitude, longitude, and assessed value from the JSON.
So: "Assessed" will turn into JSON "value"

This is the HTML file:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Edmonton Property Assessments</title>
    <link rel="stylesheet" href="style.css">
  </head>
  <body>
      <h1>Map View</h1>
      <div id="map"></div>
      <script src="script.js"></script>
      <script
          async
          src="https://maps.googleapis.com/maps/api/js?key=UR_KEY&callback=initMap">   
      </script>
  </body>
</html>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

聊慰 2025-01-26 15:07:39

由于该文件内容的解析值只能在Fetch的分辨率内提供,因此您可以将以下逻辑移至最终然后在中。

但是,由于initmap被调用(作为库的已加载回调),而无需期望任何返回值,因此您可以更改其声明为async,而不必担心破坏其他部分。

在异步函数中,您可以执行

async function initMap() {
   const map=new google.maps.Map(etc etc)
   const contents = await fetch(',/src/mapview/properties.json')
                                  .then(res=>res.json())
  // the rest of your logic
}

并获取该文件的内容作为对象。确保使用该JSON的公共URL。在适当的情况下,相对路径肯定会起作用,但是在处理事先已知的本地文件时,绝对URL会使您的生活更加轻松。

在这一点上,contents.properties保留:

[
 {
  "latitude":"53.542637347578406",
  "longitude":"-113.51709427725768",
  "account":"1061985",
  "value":"$500"
 },
 {
  "latitude":"53.5384925504052",
  "longitude":"-113.520385218556",
  "account":"1248558",
  "value":"$500"
 }
]

您将穿越实际打印标记,

let propertyMarkers=[]
for(let property_entry of contents.properties) {
  let {latitude, longitude, ...markerValues} = property_entry
  propertyMarkers.push(
     new google.maps.Marker({
        position:{
          lat:Number(latitude), 
          lng: Number(longitude)
        },
        map 
     })
  )
}

我不仅创建标记,还将它们存储在数组中。对于此示例不是强制性的,但它将允许您进一步对其进行操作。

请注意,我将您的数字坐标抛入实际数字。由于我不知道您打算如何使用其他属性或填充缺失的属性(例如图标SVG名称),所以我只是填充Markervalues,而不是任何不纬度和经度的。如您所见,请使用它。

最终警告:我没有处理错误。

响应后警告:您的评论和问题点在不同的方向上。您需要

  1. 处理异步数据检索
  2. 地图将条目数组纳入您的合适的选择结构,
  3. 从该已知结构创建标记

开始,首先要确保我将入口标记放在地图上,然后再将其他逻辑添加到混音中。

Since the parsed value of that file's content will only be available inside fetch's resolution, you could move any following logic to be inside the final then.

However, since initMap is invoked (as the library's loaded callback) without expecting any return value, you can change it's declaration to be async without worrying about breaking other parts.

Inside an async function you could do

async function initMap() {
   const map=new google.maps.Map(etc etc)
   const contents = await fetch(',/src/mapview/properties.json')
                                  .then(res=>res.json())
  // the rest of your logic
}

and get that file's content, as an object. Make sure you use the public url to that json. The relative path would work, sure, under the right circumstances, but absolute urls will make your life much easier when dealing with locally stored files whose location is known beforehand.

At this point, contents.properties holds:

[
 {
  "latitude":"53.542637347578406",
  "longitude":"-113.51709427725768",
  "account":"1061985",
  "value":"$500"
 },
 {
  "latitude":"53.5384925504052",
  "longitude":"-113.520385218556",
  "account":"1248558",
  "value":"$500"
 }
]

Which you would traverse to actually print your markers

let propertyMarkers=[]
for(let property_entry of contents.properties) {
  let {latitude, longitude, ...markerValues} = property_entry
  propertyMarkers.push(
     new google.maps.Marker({
        position:{
          lat:Number(latitude), 
          lng: Number(longitude)
        },
        map 
     })
  )
}

I'm not just creating the markers but also storing them in an array. Not mandatory for this example but it will allow you to operate on them further on.

Please note I'm casting your numeric coordinates to actual numbers. Since I don't know how are you planning to use other properties, or populate missing ones (like the icon svg name) I'm just populating markerValues with anything that's not latitude and longitude. Use it as you see fit.

Final caveat: I'm not handling errors.

Post response caveat: Your comments and your question point in different directions. You need to

  1. handle asynchronous data retrieval
  2. map the entries array into your a suitable structure of choice
  3. create markers from that known structure

Start by making sure I're putting entry markers on the map, before throwing additional logic to the mix.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文