首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >当用户更改位置或坐标更改时,更新地图上标记的位置

当用户更改位置或坐标更改时,更新地图上标记的位置
EN

Stack Overflow用户
提问于 2020-03-29 20:15:26
回答 1查看 612关注 0票数 0

日安!我有一个使用cordova (html和javascript)的原生应用程序。我需要帮助移动地图上的标记在用户改变其位置或坐标变化的实时方式。

下面是mapping.js的完整源代码

代码语言:javascript
运行
复制
var mbAttr =
    'Map data &copy; <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors, ' +
    '© <a href="https://www.mapbox.com/">Mapbox</a>',
  mbUrl =
    "https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4NXVycTA2emYycXBndHRqcmZ3N3gifQ.rJcFIG214AriISLbB6B5aw";

var redIcon = new L.Icon({
  iconUrl:
    "https://cdn.rawgit.com/pointhi/leaflet-color-markers/master/img/marker-icon-2x-red.png",
  shadowUrl:
    "https://cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.7/images/marker-shadow.png",
  iconSize: [25, 41],
  iconAnchor: [12, 41],
  popupAnchor: [1, -34],
  shadowSize: [41, 41]
});

var violetIcon = new L.Icon({
  iconUrl:
    "https://cdn.rawgit.com/pointhi/leaflet-color-markers/master/img/marker-icon-2x-violet.png",
  shadowUrl:
    "https://cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.7/images/marker-shadow.png",
  iconSize: [35, 51],
  iconAnchor: [17, 51],
  popupAnchor: [1, -34],
  shadowSize: [51, 51]
});

var streets = L.tileLayer(mbUrl, { id: "mapbox.streets", attribution: mbAttr });

var mymap;
var locationHistory = [];
var watch;

function f1(a, b) {
  lat = a;
  lon = b;

  mymap = L.map("mapid", {
    center: [14.54965, 121.00737],
    zoom: 16,
    layers: [streets]
  });

  L.marker([14.4311, 120.9682], { icon: violetIcon })
    .addTo(mymap)
    .bindPopup("New Bacoor City Hall");

  L.marker([a, b], { icon: redIcon })
    .addTo(mymap)
    .bindPopup("You are here.")
    .openPopup()
    .update();
}


function getLocation() {
  navigator.geolocation.getCurrentPosition(showPosition, showError);
}

function showPosition(position) {
  f1(position.coords.latitude, position.coords.longitude);
}

function showHistory() {
  var el = document.getElementById("historyWrapper");
  if (el.style.display === "none") {
    el.style.display = "block";
  } else {
    el.style.display = "none";
  }
}

function startWatching() {
  var toastHTML = "Tracking started...";
  M.toast({html: toastHTML, displayLength: 3000});
  watch = navigator.geolocation.watchPosition(onSuccess, onError, {
    maximumAge: 10000,
    timeout: 5000,
    enableHighAccuracy: true
  });
  var el = document.getElementById("historyWrapper");
  el.style.display = "none";
}

function stopWatching() {
  if (confirm("Do you want to stop tracking?")) {
    var toastHTML = "Tracking Stopped.";
    M.toast({html: toastHTML, displayLength: 3000});
    navigator.geolocation.clearWatch(watch);
    var el = document.getElementById("locationHistory");
    locationHistory.forEach(function(location) {
      el.innerHTML =
        "<li>Latitude: " +
        location.coords.latitude +
        "<br />" +
        "Longitude: " +
        location.coords.longitude +
        "<br />" +
        "<strong>Date: " +
        new Date().toLocaleString() +
        "</strong><hr /></li>" +
        el.innerHTML;
    });
    document.getElementById("historyWrapper").style.display = "block";

    document.getElementById("geolocation").innerHTML = "";
  }
}

function showError(error) {
  switch (error.code) {
    case error.PERMISSION_DENIED:
      var toastHTML = "User denied the request for geolocation.";
      M.toast({html: toastHTML, displayLength: 3000});
      break;
    case error.POSITION_UNAVAILABLE:
      var toastHTML = "Location information is unavailable.";
      M.toast({html: toastHTML, displayLength: 3000});
      break;
    case error.TIMEOUT:
      var toastHTML = "The request to get user location timed out.";
      M.toast({html: toastHTML, displayLength: 3000});
      break;
    case error.UNKNOWN_ERROR:
      var toastHTML = "An unknown error occurred.";
      M.toast({html: toastHTML, displayLength: 3000});
      break;
  }
  window.close();
}

function onSuccess(position) {
  locationHistory.push(position);
  var element = document.getElementById("geolocation");
  element.innerHTML = "";
  element.innerHTML =
    "Latitude: " +
    position.coords.latitude +
    "<br />" +
    "Longitude: " +
    position.coords.longitude +
    "<br />" +
    "<hr />" +
    element.innerHTML;
}

function onError(error) {
  var toastHTML = "code: " + error.code + "\n" + "message: " + error.message + "\n";
  M.toast({html: toastHTML, displayLength: 3000});
}

getLocation();

因此,我的html文件上有3个按钮,它们调用js文件中的3个函数- startWatching()stopWatching()showHistory()

当用户移动或改变位置时,function startWatching()将监视坐标。function stopWatching()将停止监视或获取坐标。function showHistory()将显示所监视的坐标列表。

getLocation() var violetIcon是已定义位置的标记之后,var redIcon是用户位置的标记

function getLocation()发生时,function f1(a, b)将在地图上显示2个标记-一个标记表示定义的位置,另一个标记表示用户的位置。

现在,当用户更改其位置或在地图上生成新坐标时,我需要移动用户位置的标记。我希望有人能在这方面帮助我。提前感谢`

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-03-29 20:55:34

您需要在f1函数之外访问您的用户标记。您可以通过将标记分配给全局定义的变量来完成此操作。

在全局范围内定义您的标记变量。

代码语言:javascript
运行
复制
var userMarker = null;

在您的f1函数中,将创建的标记赋给userMarker变量。

代码语言:javascript
运行
复制
function f1(a, b) {
  ...
  userMarker = L.marker([a, b], { icon: redIcon })
    .addTo(mymap)
    .bindPopup("You are here.")
    .openPopup()
    .update();
}

现在,当用户的位置更新后,您可以在onSuccess函数中使用userMarker标记实例。使用setLatLng()方法使用新坐标更新标记的位置。

代码语言:javascript
运行
复制
function onSuccess(position) {
  // Destructure assignment to get the lat and long from the position object.
  let { latitude, longitude } = position.coords;
  if (userMarker !== null) {
    userMarker.setLatLng([latitude, longitude]);
  }
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60914119

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档