Google Maps API重新加载标记位置。

huangapple go评论75阅读模式
英文:

Google Maps API reload marker location

问题

我有一个地图,根据一个 .json 文件中的车辆 GPS 位置绘制标记。我遇到了一个问题,无法让地图自动重新加载来自 .json 文件的数据,然后根据新数据/位置重新绘制标记。以下是我的代码部分摘录:

这是获取来自 .json 文件位置的 fetch 调用,它正常工作;我确认如果 .json 文件更改,它会带入这些更改。我添加了一个 setInterval 每 5 秒触发一次以获取新的位置数据。接下来我构建地图并导入数据:

我将创建标记的代码包装到一个函数中,然后使用 setInterval 每 5 秒触发一次。

无论是 fetch 还是 setmarker 代码都按预期自动运行,问题是我无法将来自 fetch 调用的更新位置信息倾入到 "data" 声明中。我还怀疑我需要添加代码来删除所有标记,然后重新绘制它们;但是如果没有从 fetch 获取更新的位置数据,这是一个无意义的点。
英文:

I have a map that is drawing markers for vehicles based on their GPS location inside a .json file. I'm running into problems getting the map to automatically reload the data from the .json file and then redraw the markers based on the new data/location. Here is some excerpts of my code:

const fetchAPI = async () => {
  const url = './cradlepoint.json';
  const response = await fetch(url);
  const locations = await response.json();
  return locations;
};

let data = await fetchAPI();
setInterval(fetchAPI,5000);

This is the fetch call that gets the location from the .json file and that's working fine; I confirmed that if the .json file changes, it brings in those changes. I added a setInterval to fire that every 5 seconds to grab new location data. Next I build the map and import that data:

async function initMap() {
    const { Map, InfoWindow, KmlLayer } = await google.maps.importLibrary("maps");
    const { Marker } = await google.maps.importLibrary("marker");
    map = new Map(document.getElementById("map"), {
      mapId: "####",
      center: { lat: ###, lng: ### },
      zoom: 14,
    });

  const busicon = "https://maps.google.com/mapfiles/ms/icons/bus.png";
  
  const infoWindow = new InfoWindow();

  function setMarker() {
  var results = data.data.length
  for (let i = 0; i < results; i++){
    var busid = data.data[i].id;
    var buslat = data.data[i].latitude;
    var buslong = data.data[i].longitude;
    const marker = new Marker({
      map: map,
      position: { lat: buslat, lng: buslong },
      icon: busicon,
      title: busid
    });
    // Add a click listener for each marker, and set up the info window.
    marker.addListener("click", ({ domEvent, latLng }) => {
    const { target } = domEvent;

    infoWindow.close();
    infoWindow.setContent(marker.title);
    infoWindow.open(marker.map, marker);
    });
  };
  };

  setMarker()
  setInterval(setMarker,5000)

initMap();

I wrapped my create marker code into a function and then used setInterval to fire that every 5 seconds.

Both the fetch and the setmarker code is automatically running as expected, the problem is I can't get the updated location info coming out of the fetch call to dump into the "data" declaration. I also suspect I need to add code to delete all markers and then re-draw them; but without getting the updated location data from the fetch, that's a moot point.

答案1

得分: 0

为什么不用 `let data = await fetchAPI();` ? 我怀疑你的问题是要将所有这些函数构造成一个每隔 5 秒发生一次的过程也许像这样的伪代码

// 全局变量
let map = null;
let previous_markers = null

// 仅用于调试
function delay(millisec) {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve()
    }, millisec);
  })
}

// 获取 json 数据
async function fetch_data() {
  console.log("TODO: 获取数据");
  await delay(1000);
  return new Array(3).fill(Math.round(Math.random()*10));
}

// 设置标记
async function setMarkers(map, markers) {
  console.log("TODO: 在地图上设置标记: " + markers);
}

// 移除标记
async function removeMarkers(map, markers) {
  console.log("TODO: 从地图上移除标记: " + previous_markers);
}

// google 地图
function Map() {
  return "地图";
}

// 初始化地图,绘制地图,移除标记,绘制标记 
async function draw_map(markers) {
  if (map == null) {
    console.log("TODO: 初始化地图")
    map = new Map();
  }
  
  if (previous_markers) {
    removeMarkers(map, previous_markers);
  }
  
  setMarkers(map, markers)

  previous_markers = markers;
}

// 每 5 秒运行一次的过程函数
async function fetch_and_draw() {
  let markers = await fetch_data();
  draw_map(markers);
}

// 主程序:
fetch_and_draw();
setInterval(fetch_and_draw, 5000);
英文:

Why not let data = await fetchAPI(); ? I suspect your problem is to construct all those functions into one process that occurs every 5 seconds? Maybe something like this pseudo-code:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

// globals
let map = null;
let previous_markers = null
// just for debug
function delay(millisec) {
return new Promise(resolve =&gt; {
setTimeout(() =&gt; {
resolve()
}, millisec);
})
}
// fetching the json
async function fetch_data() {
console.log(&quot;TODO: fetch data&quot;);
await delay(1000);
return new Array(3).fill(Math.round(Math.random()*10));
}
// setting markers
async function setMarkers(map, markers) {
console.log(&quot;TODO: set markers on map: &quot; + markers);
}
// removing markers
async function removeMarkers(map, markers) {
console.log(&quot;TODO: remove markers from map: &quot; + previous_markers);
}
// google map
function Map() {
return &quot;map&quot;;
}
// init map, draw map, remove markers, draw markers 
async function draw_map(markers) {
if (map == null) {
console.log(&quot;TODO: init map&quot;)
map = new Map();
}
if (previous_markers) {
removeMarkers(map, previous_markers);
}
setMarkers(map, markers)
previous_markers = markers;
}
// the process function every 5 seconds
async function fetch_and_draw() {
let markers = await fetch_data();
draw_map(markers);
}
// main:
fetch_and_draw();
setInterval(fetch_and_draw, 5000);

<!-- end snippet -->

答案2

得分: 0

看起来在调用fetchAPI()时,你没有更新"data"变量的新位置信息。
你每隔5秒钟调用fetchAPI,但没有将新值赋给"data"。
然后你可以改成:

let data;

const fetchAPI = async () => {
    //...
    //...
    //...
    //...
    const locations = await response.json();
    data = locations;
};
英文:

It seems that you are not updating the "data" variable with the new locations when calling to the fetchAPI ().
You are calling fetchAPI every 5 seconds but not assigning new values to "data".
Then you can change to :

let data;
const fetchAPI = async () =&gt; {
//...
//...
//...
//...
const locations = await response.json();
data = locations;
};

huangapple
  • 本文由 发表于 2023年7月18日 04:36:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/76707914.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定