Leafletjs地图元素事件触发查找坐标点并打开popup

应用场景非常多,比如airbnb上面的民宿列表,点击就能在地图上显示坐标,本文就该功能用leaflet来实现。

示例一 jQuery

演示地址1演示地址2

最新示例代码:

多个标注

    <!-- the map div holds the map -->
    <div id="map"></div>
    <div id="stations">
      <!-- the stations div holds a list of the stations marked on the map -->
      <b style="color:red; text-decoration: underline;">Net #886</b><br><a id='marker_1' href='#'>N0SAX</a><br><a id='marker_2' href='#'>KF0ED</a><br><a id='marker_3' href='#'>KD0ZMG</a><br><a id='marker_4' href='#'>KC0NOX</a><br><a id='marker_5' href='#'>AA0JA</a><br>
      <a
        id='marker_6' href='#'>AC0OK</a><br><a id='marker_7' href='#'>KG6TUB</a><br><a id='marker_9' href='#'>NCMO</a><br><a id='marker_10' href='#'>AC0TQ</a><br><a id='marker_11' href='#'>KE0MGD</a><br><a id='marker_12' href='#'>KE0ELB</a><br><a id='marker_13' href='#'>W0WHH</a><br>
        <a
          id='marker_14' href='#'>AD0YN</a><br><a id='marker_15' href='#'>KE0RTA</a><br> </div>


    <script>
      var map = null;
      var zoomLevel = 10;
      var markers = [];
      var fg = new L.featureGroup();
      var bounds = new L.latLngBounds;
      // starting point for the map and a zoom level of 20

      var map = L.map('map').setView([39.202903, -94.602907], zoomLevel);

      L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4NXVycTA2emYycXBndHRqcmZ3N3gifQ.rJcFIG214AriISLbB6B5aw', {
        maxZoom: zoomLevel,
        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>',
        id: 'mapbox.streets'
      }).addTo(map);
      fg.addTo(map);
      $(document).ready(function() {
        function netStationLocations(e) {

          // This is the markers array
          //	var markers = []; 
          var N0SAX = L.marker([39.3762884, -93.496261], {
            title: "marker_1"
          }).addTo(fg).bindPopup("1<br><b>#233</b><br>N0SAX<br>Jack Vantrump<br>Carroll  Co., MO Dist: A<br>39.3762884, -93.496261<br>EM39GJ");
          markers.push(N0SAX);

          var KF0ED = L.marker([39.7898224, -93.558050], {
            title: "marker_2"
          }).addTo(fg).bindPopup("2<br><b>#245</b><br>KF0ED<br>Glenn O connor<br>	 	Livingston	 Co., MO Dist: H<br>39.7898224, -93.558050<br>EM39FS");
          markers.push(KF0ED);

          var KD0ZMG = L.marker([39.010151, -94.579769], {
            title: "marker_3"
          }).addTo(fg).bindPopup("3<br><b>#264</b><br>KD0ZMG<br>	 	 THEARL 	 Speck<br>Livingston  Co., MO Dist: H<br>39.010151, -94.579769<br>EM29RA");
          markers.push(KD0ZMG);

          var KC0NOX = L.marker([39.8132645, -93.558613], {
            title: "marker_4"
          }).addTo(fg).bindPopup("4<br><b>#387</b><br>KC0NOX<br>Joe Dietrick<br>Livingston  Co., MO Dist: H<br>39.8132645, -93.558613<br>EM39FT");
          markers.push(KC0NOX);

          var AA0JA = L.marker([39.593217, -93.788696], {
            title: "marker_5"
          }).addTo(fg).bindPopup("5<br><b>#389</b><br>AA0JA<br>Bill Whitlock<br>Caldwell  Co., MO Dist: H<br>39.593217, -93.788696<br>EM39co");
          markers.push(AA0JA);

          var AC0OK = L.marker([40.1697444, -93.093104], {
            title: "marker_6"
          }).addTo(fg).bindPopup("6<br><b>#414</b><br>AC0OK<br>Sam Cook<br>Sullivan  Co., MO Dist: B<br>40.1697444, -93.093104<br>EN30KE");
          markers.push(AC0OK);

          var KG6TUB = L.marker([39.7973405, -93.551737], {
            title: "marker_7"
          }).addTo(fg).bindPopup("7<br><b>#610</b><br>KG6TUB<br>Doris Hoch<br>Livingston  Co., MO Dist: H<br>39.7973405, -93.551737<br>EM39FT");
          markers.push(KG6TUB);

          var NCMO = L.marker([40.0706749, -93.611323], {
            title: "marker_9"
          }).addTo(fg).bindPopup("9<br><b>#614</b><br>NCMO<br>Glendale (KB0RPJ) Briggs<br>Grundy  Co., MO Dist: <br>40.0706749, -93.611323<br>EN30EB");
          markers.push(NCMO);

          var AC0TQ = L.marker([39.7973405, -93.551737], {
            title: "marker_10"
          }).addTo(fg).bindPopup("10<br><b>#616</b><br>AC0TQ<br>Ken Hoch<br>Livingston  Co., MO Dist: H<br>39.7973405, -93.551737<br>EM39FT");
          markers.push(AC0TQ);

          var KE0MGD = L.marker([39.8157137, -94.020960], {
            title: "marker_11"
          }).addTo(fg).bindPopup("11<br><b>#621</b><br>KE0MGD<br>Carl Russell<br>Daviess  Co., MO Dist: H<br>39.8157137, -94.020960<br>EM29XT");
          markers.push(KE0MGD);

          var KE0ELB = L.marker([40.2363229, -93.153805], {
            title: "marker_12"
          }).addTo(fg).bindPopup("12<br><b>#623</b><br>KE0ELB<br>Kris Good<br>Sullivan  Co., MO Dist: B<br>40.2363229, -93.153805<br>EN30KF");
          markers.push(KE0ELB);

          var W0WHH = L.marker([40.1931446, -93.667155], {
            title: "marker_13"
          }).addTo(fg).bindPopup("13<br><b>#624</b><br>W0WHH<br>Bill Hein<br>Grundy  Co., MO Dist: H<br>40.1931446, -93.667155<br>EN30DE");
          markers.push(W0WHH);

          var AD0YN = L.marker([39.659816, -93.398354], {
            title: "marker_14"
          }).addTo(fg).bindPopup("14<br><b>#644</b><br>AD0YN<br>Charles STIRLING<br>Livingston  Co., MO Dist: H<br>39.659816, -93.398354<br>EM39HP");
          markers.push(AD0YN);

          var KE0RTA = L.marker([40.0722144, -93.578824], {
            title: "marker_15"
          }).addTo(fg).bindPopup("15<br><b>#673</b><br>KE0RTA<br>Vic Markell<br>Grundy  Co., MO Dist: H<br>40.0722144, -93.578824<br>EN30FB");
          markers.push(KE0RTA);

          fg.eachLayer(function(layer) {
            bounds.extend(layer.getLatLng());
          });





          // Set up to show markers popup
          function markerFunction(id) {
            for (var i in markers) {
              var markerID = markers[i].options.title;
              if (markerID == id) {
                markers[i].openPopup();
              };
            } // end of for loop
          } // end markerFunction 

          // JQuery call to display the popup from the marker list
          $("a").click(function() {
            markerFunction($(this)[0].id);
          });

        } // End of the netStationLocations function

        // In case some errors pop up
        function onLocationError(e) {
          alert(e.message);
        }


        //	map.on('locationfound', netStationLocations);
        //	map.on('locationerror', onLocationError);

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

        netStationLocations();

        map.fitBounds(bounds, {
          padding: [1.5, 1.5]
        });

        // Zoom to fit all markers

        // var fg = new L.featureGroup([[39.3762884,-93.496261],[39.7898224,-93.558050],[39.010151,-94.579769],[39.8132645,-93.558613],[39.593217,-93.788696],[40.1697444,-93.093104],[39.7973405,-93.551737],[40.0706749,-93.611323],[39.7973405,-93.551737],[39.8157137,-94.020960],[40.2363229,-93.153805],[40.1931446,-93.667155],[39.659816,-93.398354],[40.0722144,-93.578824]]); 

      });

    </script>

单标注

html

<div id="map" style="width:500px;height:400px;"></div>
<a id="marker_1" href="#">Marker 1</a><br>

js

var map = L.map('map').setView([51.495, -0.09], 15);
var osmUrl = 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png';
    var osmLayer = new L.TileLayer(osmUrl, {
        maxZoom: 19,
        attribution: 'Map data © OpenStreetMap contributors'
    });
map.addLayer(osmLayer);
    var markers = [];
    var marker1 = L.marker([51.497, -0.09],{title:"marker_1"}).addTo(map).bindPopup("Marker 1");
    markers.push(marker1);
    
    marker1.on('mouseover',function(ev) {
      marker1.openPopup();
    });
    
    
    function markerFunction(id){
        for (var i in markers){
            var markerID = markers[i].options.title;
            if (markerID == id){
                markers[i].openPopup();
            };
        }
    }
    
    $("a").click(function(){
        markerFunction($(this)[0].id);
    });

示例二 React

演示地址

import React, { useEffect, useState } from "react";
import { MapContainer, TileLayer, Marker, Popup } from "react-leaflet";
import "leaflet/dist/leaflet.css";
import { Icon } from "leaflet";
import FakeData from "../data";
import { Div, PopContainer } from "./mapStyle";
import markerIcon from "../public/markerIcon.png";

const MarkerIcon = new Icon({
  iconUrl: markerIcon,
  iconSize: [50, 50]
});

function MapBox({ cardItem }) {
  const [nurse, setNurse] = useState(null);
  const bull = <span>•</span>;
  const [map, setMap] = useState(null);

  useEffect(() => {
    if (!cardItem || !map) return;
    const { coordonatelat, coordonatelng } = cardItem;
    // map.setView([coordonatelat, coordonatelng], 13);
    map.flyTo([coordonatelat, coordonatelng]);
  }, [cardItem, map]);

  return (
    <Div>
      <MapContainer
        center={[50.6365654, 3.0635282]}
        zoom={13}
        scrollWheelZoom={false}
        whenCreated={setMap}
      >
        <TileLayer
          attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
          url="https://{s}.tile.openstreetmap.de/tiles/osmde/{z}/{x}/{y}.png"
        />
        {FakeData.map((data) => (
          <Marker
            key={data.id}
            icon={MarkerIcon}
            position={[data.coordonatelat, data.coordonatelng]}
            onmouseover={() => setNurse(data)}
          />
        ))}
        {nurse && (
          <Popup
            position={[nurse.coordonatelat, nurse.coordonatelng]}
            onClose={() => {
              setNurse(null);
            }}
            closeButton={false}
          >
            <PopContainer>
              <h2>
                {bull}
                {nurse.first_name} {nurse.last_name}
                {bull}
              </h2>
              <h3>{nurse.job}</h3>
              <p>
                {" "}
                {nurse.address}
                <br />
                {nurse.phone_number}
              </p>
            </PopContainer>
          </Popup>
        )}
      </MapContainer>
    </Div>
  );
}

export default MapBox;

Post Comment