首页 > 解决方案 > 当我允许跟踪我的位置时,尝试在我的确切位置上显示自定义标记

问题描述

当我接受询问位置的提示时,我想在我的位置上使用图片userPosition.png,现在它不起作用。

<!DOCTYPE html>
<html lang="en">
  <head>
    <link
      rel="stylesheet"
      href="https://unpkg.com/leaflet@1.6.0/dist/leaflet.css"
      integrity="sha512-xwE/Az9zrjBIphAcBb3F6JVqxf46+CDLwfLMHloNu6KEQCAWi6HcDUbeOfBIptF7tcCzusKFjFw2yuvEpDL9wQ=="
      crossorigin=""
    />
    <script
      src="https://unpkg.com/leaflet@1.6.0/dist/leaflet.js"
      integrity="sha512-gZwIG9x3wUXg2hdXF6+rVkLF/0Vi9U8D2Ntg4Ga5I5BZpVkVxlJWbSQtXPSiUTtC0TjtGOmxa1AJPuV0CPthew=="
      crossorigin=""
    ></script>
    <script src="./leaflet/leaflet.js"></script>
    <style></style>
  </head>

  <body>
    <h2 style="text-align: center;">My interactive map</h2>

    <div id="mapid" style="width: 100%;height: 500px;"></div>

    <script>
      var mymap;
      mymap = L.map("mapid").setView([55.70584, 13.19021], 12);

      L.tileLayer(
        "https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token=pk.eyJ1IjoibWFkc2pvaGFuc2VuIiwiYSI6ImNrNWkxZnA3bzA5NnIza3M2cGczNnprMHcifQ.Z2h9R1lODB6zPZ2Ex92BrA",
        {
          attribution:
            'Map data &copy; <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="https://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="https://www.mapbox.com/">Mapbox</a>',
          maxZoom: 18,
          id: "mapbox/streets-v11",
          accessToken: "your.mapbox.access.token"
        }
      ).addTo(mymap);

      function onLocationFound(e) {
        var radius = e.accuracy / 2;

        L.marker(e.latlng)
          .addTo(map)
          .bindPopup("You are within " + radius + " meters from this point")
          .openPopup();
      }

      function onLocationError(e) {
        alert(e.message);
      }

      map.on("locationfound", onLocationFound);
      map.on("locationerror", onLocationError);

      map.locate({
        setView: true,
        maxZoom: 16
      });

      var popup = L.popup();
      var marker = L.marker();
      var circle = L.circle();

      var newMarkerIcon = L.Icon.extend({
        options: {
          iconSize: [38, 95],
          shadowSize: [50, 64],
          iconAnchor: [22, 94],
          shadowAnchor: [4, 62],
          popupAnchor: [-3, -76]
        }
      });

      var blackMarker = new newMarkerIcon({ iconUrl: "userPosition.png" });

      function onMapClick(e) {
        L.marker(e.latlng, "Insert postition PNG pic here")
          .addTo(mymap)
          .bindPopup("You clicked the map at " + e.latlng.toString());
      }

      mymap.on("click", onMapClick);
    </script>
  </body>
</html>

标签: leaflet

解决方案


用这个 :

L.marker([e.latlng], { icon: YourIconHere })
        .bindPopup("You are within " + radius + " meters from this point")
        .openPopup()
        .addTo(map);

您也可以像这样添加圆圈:

L.circle([e.latlng], radius,
      { weight: 1, color: 'blue', fillColor: '#cacaca', fillOpacity: 0.2 })
      .addTo(map);

推荐阅读