首页 > 解决方案 > 在 Map 和 navigator.geolocation 上使用 Leaflet 的多个事件

问题描述

我正在尝试获取Leaflet地图上发生的三个事件:

1Leaflet使用单个 实例化地图marker,这也是地图的中心。

2navigator.geolocation.getCurrentPosition用于获取用户位置,该位置会更新lat/lon表单字段,并marker在地图上放置另一个coordinates

3 单击地图后,插入第三个marker,再次更新纬度/经度表单字段。

我知道navigator.geolocation.getCurrentPosition是异步的,所以这必须包含几乎所有内容。

当前:我已经完成了第一点。我没有得到navigator.geolocation.getCurrentPosition marker,但表格确实更新了。我也不能点击新的第三个pointer marker

问题:我怎样才能让所有三个标记都正常工作?

<div id="warning"></div>

<form method="post" action="#" name="meform">
  <label for="latFld">Lat/Lon</label>
  <input type="text" name="mylat" id="lat" value="44.444" readonly>,<input type="text" name="mylon" id="lon" value="-79.999" readonly> acc: <input type="text" name="myacc" id="acc" value="" readonly> metres
</form>

<div class="row">
  <div class="col-md-12">
    <div id="mapid" style="width: 95%; height: 500px;"></div>
  </div>
</div>

<script>

var homeIcon = L.icon({
  iconUrl:      '/img/house_marker.png',
  iconSize:     [24, 24],
  iconAnchor:   [12, 24],
  popupAnchor:  [0, -24]
  });
var mymarkers = L.layerGroup([
  L.marker([ 43.669128, -79.343001 ], {icon: homeIcon}).bindPopup("Get Gas Here")
  ]);

function foundLocation(pos) {
  myLat = pos.coords.latitude;
  myLon = pos.coords.longitude;
  myAcc = pos.coords.accuracy;
  document.getElementById("lat").value = myLat;         // form field
  document.getElementById("lon").value = myLon;         // form field
  document.getElementById("acc").value = myAcc;         // form field

  var mymap = L.map('mapid', {
    center:       [ 43.669128, -79.343001 ],
    minZoom:      2,
    maxZoom:      18,
    zoom:         15,
    layers: [mymarkers]
    });

  L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4NXVycTA2emYycXBndHRqcmZ3N3gifQ.rJcFIG214AriISLbB6B5aw', {
        attribution: 'Map data &copy; <a href="http://openstreetmap.org" target="_blank">OpenStreetMap</a> Imagery © <a href="http://mapbox.com" target="_blank">Mapbox</a>',
        id: 'mapbox.streets'
      }).addTo(mymap);

  L.control.layers(mymarkers).addTo(mymap);
  console.log("alpha");

  L.marker([ myLat, myLon ], {icon: homeIcon}).bindPopup("We measured you here<br>Accuracy: " + myAcc + " metres").addTo(mymarkers);

  mymap.on('click', function(e) {
  alert("clicked");
    document.getElementById("lat").value = e.latlng.lat;
    document.getElementById("lon").value = e.latlng.lng;
    L.marker([e.latlng.lat,e.latlng.lng]).bindPopup('Chosen Location').addTo(mymarkers);
    $('#warning').html("Values updated");
    });

  };

function noLocation() {
  document.getElementById("warning").innerHTML = "Could not find your location";
  };

options = {
  enableHighAccuracy:     true,
  timeout:                5000,
  maximumAge:             0
  };

navigator.geolocation.getCurrentPosition(foundLocation, noLocation, options);

</script>

标签: javascriptleafletopenstreetmapw3c-geolocation

解决方案


解决了

<script>
var myLat = -79.999
var myLon = 44.444

var homeIcon = L.icon({
  iconUrl:      '/img/house_marker.png',
  iconSize:     [24, 24],
  iconAnchor:   [12, 24],
  popupAnchor:  [0, -24]
  });
var mymarkers = L.layerGroup([
  L.marker([ 43.669128, -79.343001 ], {icon: homeIcon}).bindPopup("Get Gas Here")
  ]);
var chosenmarker = L.layerGroup([
  ]);

function foundLocation(pos) {
  myLat = pos.coords.latitude;
  myLon = pos.coords.longitude;
  myAcc = pos.coords.accuracy;
  document.getElementById("lat").value = myLat;         // form field
  document.getElementById("lon").value = myLon;         // form field
  document.getElementById("acc").value = myAcc;         // form field

  L.marker([ myLat, myLon ], {icon: homeIcon}).bindPopup("We measured you here<br>Accuracy: " + myAcc + " metres").addTo(mymarkers);

  var mymap = L.map('mapid', {
    center:       [ 43.669128, -79.343001 ],
    minZoom:      2,
    maxZoom:      18,
    zoom:         15,
    layers: [mymarkers, chosenmarker]
    });
  L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4NXVycTA2emYycXBndHRqcmZ3N3gifQ.rJcFIG214AriISLbB6B5aw', {
        attribution: 'Map data &copy; <a href="http://openstreetmap.org" target="_blank">OpenStreetMap</a> Imagery © <a href="http://mapbox.com" target="_blank">Mapbox</a>',
        id: 'mapbox.streets'
      }).addTo(mymap);

  console.log("alpha");

  mymap.on('click', function(e) {
    console.log("clicked");
    chosenmarker.clearLayers();
    document.getElementById("lat").value = e.latlng.lat;            // set form fields lat
    document.getElementById("lon").value = e.latlng.lng;            // set form fields lon
    L.marker([e.latlng.lat,e.latlng.lng]).bindPopup("Chosen Location").addTo(chosenmarker);
    $('#warning').html("Values updated");
    });

  L.control.layers(mymarkers, chosenmarker).addTo(mymap);
  };

function noLocation() {
  document.getElementById("warning").innerHTML = "Could not find your location";
  };

options = {
  enableHighAccuracy:     true,
  timeout:                5000,
  maximumAge:             0
  };

navigator.geolocation.getCurrentPosition(foundLocation, noLocation, options);

</script>

首先,提供变量和layerGroupsLeaflet对象),然后启动navigator.geolocation.getCurrentPosition. latlon抓住,使用中心提供的地图latlon。然后是第二个 click-based 的实现L.marker,它触发了对L.layergroup名为selectedmarker的清除,这也更新了表单并将 amarker放置在地图上。那将永远是一个对象。这样操作数selectedmarker.clearLayers(); 不会抹去前两个硬markers


推荐阅读