javascript - how to add marker on click event in leaflet.js - Stack Overflow

i want to add marker, when i click on map.but i dont know how to do it:(by default I do not want to ha

i want to add marker, when i click on map. but i dont know how to do it:(

by default I do not want to have a marker map

i just wrote this code:

  var mapOptions = {
        center: [17.385044, 78.486671],
        zoom: 10
    }
    var layer = new L.TileLayer('http://{s}.tile.openstreetmap/{z}/{x}/{y}.png');
    var map = new L.map('mapid', mapOptions);
    map.addLayer(layer);

    var markerOptions = {
        title: "MyLocation",
        clickable: true,
        draggable: true
    }

    function onClick(e) {
        alert(this.getLatLng());
    }
    var marker = L.marker([17.385044, 78.486671], markerOptions).on('click',onClick);
    marker.addTo(map);       

i want to add marker, when i click on map. but i dont know how to do it:(

by default I do not want to have a marker map

i just wrote this code:

  var mapOptions = {
        center: [17.385044, 78.486671],
        zoom: 10
    }
    var layer = new L.TileLayer('http://{s}.tile.openstreetmap/{z}/{x}/{y}.png');
    var map = new L.map('mapid', mapOptions);
    map.addLayer(layer);

    var markerOptions = {
        title: "MyLocation",
        clickable: true,
        draggable: true
    }

    function onClick(e) {
        alert(this.getLatLng());
    }
    var marker = L.marker([17.385044, 78.486671], markerOptions).on('click',onClick);
    marker.addTo(map);       
Share Improve this question asked Sep 16, 2018 at 18:15 user9966589user9966589
Add a ment  | 

2 Answers 2

Reset to default 4
 map.on("click", function(e){
        var mp = new L.Marker([e.latlng.lat, e.latlng.lng]).addTo(map);
        alert(mp.getLatLng());
 });

If you are looking to set only one marker on the map, note that you must delete the previous one.

 var marker;
 map.on('click', function (e) {
  if (marker) { // check
   map.removeLayer(marker); // remove old layers
  }
 marker = new L.Marker(e.latlng).addTo(map); // set New Layer         
 });

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744802877a4594599.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信