【问题标题】:Loop Over Array of Lat Lng for Google Maps API循环遍历谷歌地图 API 的 Lat Lng 数组
【发布时间】:2021-12-27 21:12:58
【问题描述】:

我正在尝试使用我的数据库中的动态权重映射一组 100 多个地址。如果我用所有点和权重硬编码渲染我的地图,它会起作用,但是当我尝试在 for 循环中创建对象时,它总是给我一个错误。

Type 'object[]' is not assignable to type '(LatLng | WeightedLocation)[]'.
    Type 'object' is not assignable to type 'LatLng | WeightedLocation'.
      Type '{}' is missing the following properties from type 'WeightedLocation': location, weight

数据结构如下。

[{
  "_id": "123",
  "bounds": { "lat": 37, "lng": -122 },
  "val1": 0,
  "val2": 18
}, {
  "_id": "124",
  "bounds": { "lat": 38, "lng": -123 },
  "val1": 5,
  "val2": 100
}]

给我错误的函数是

function getPoints() {
  const data = getDataFromDB();
  var heatData : object[] = [];

  data.forEach(r => {
    console.log(r.bounds)
    const loc = new google.maps.LatLng(r.bounds.lat, r.bounds.lng)
    const newObj = {location: loc, weight: r.val1}
    heatData.push(newObj);
  })
  console.log(heatData) 

  
  return heatData;
}

编辑添加。

当我传递这个数组时,地图将呈现。我只是不知道如何创建这个数组,但我提供的数据不是硬编码的。

var heatData = [
    {location: new google.maps.LatLng(37.782, -122.447), weight: 100},
    {location: new google.maps.LatLng(37.782, -122.443), weight: 2},
    {location: new google.maps.LatLng(37.782, -122.441), weight: 3},
    {location: new google.maps.LatLng(37.782, -122.439), weight: 2},
    {location: new google.maps.LatLng(37.782, -122.435), weight: 0.5},
    {location: new google.maps.LatLng(37.785, -122.447), weight: 3},
    {location: new google.maps.LatLng(37.785, -122.445), weight: 2},
    {location: new google.maps.LatLng(37.785, -122.441), weight: 0.5},
    {location: new google.maps.LatLng(37.785, -122.437), weight: 2},
    {location: new google.maps.LatLng(37.785, -122.435), weight: 3}
  ];

【问题讨论】:

  • 您的LatLngWeightedLocation 看起来如何? Typescript 似乎在抱怨 heatData 中的元素与其中任何一个都不兼容。
  • heatData 应该是一个数组吗?为什么要这样定义?

标签: javascript google-maps-api-3


【解决方案1】:

我认为您打算将heatData 输入为(LatLng | WeightedLocation)[] 而不是object[]

var heatData : (LatLng | WeightedLocation)[] = [];

【讨论】:

    【解决方案2】:

    只需替换

    var heatData : object[] = [];
    

    const heatData = [];
    

    它会做的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-15
      相关资源
      最近更新 更多