Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

leaflet: how to disable zoom event after using boxzoom (shift + move mouse)

After selecting an area and the 'boxzoomend' event is done, the 'zoomstart' event is trigger.

Anyone know how to disable this zoom event to occur?

map.on('boxzoomend', function(e) {
console.log('box zoom end', e);});


map.on('zoomstart', function(e) {
console.log('zoom start', e);});

Please see this demo: http://jsfiddle.net/5VLJU/324/

I don't want to zoom after selecting the area, i want to use the zoom box functionality to be able to select markers which will be inside the selected area.

Zoom Box image example

TO SELECT AREA: Shift + move mouse

Thanks

like image 520
user3341337 Avatar asked Jul 03 '17 10:07

user3341337


2 Answers

You can rewrite the _onMouseUp function

$(function() {
L.Map.BoxZoom.prototype._onMouseUp = function (e) {
    if ((e.which !== 1) && (e.button !== 1)) { return; }

    this._finish();

    if (!this._moved) { return; }
    // Postpone to next JS tick so internal click event handling
    // still see it as "moved".
    this._clearDeferredResetState();
    this._resetStateTimeout = setTimeout(L.Util.bind(this._resetState, this), 0);

    var bounds = new L.LatLngBounds(
        this._map.containerPointToLatLng(this._startPoint),
        this._map.containerPointToLatLng(this._point)
    );
    this._map.fire('boxzoomend', {boxZoomBounds: bounds})

    if (!this._map.options.noFit) {
        this._map.fitBounds(bounds);
    }
};

// We’ll add a OSM tile layer to our map
var osmUrl = 'http://{s}.tile.osm.org/{z}/{x}/{y}.png',
    osmAttrib = '&copy; <a href="http://openstreetmap.org/copyright">OpenStreetMap</a> contributors',
    osm = L.tileLayer(osmUrl, {
        maxZoom: 18,
        attribution: osmAttrib
    });


// initialize the map on the "map" div with a given center and zoom
var map = L.map('map',{noFit:true}).setView([25.92, 79.84], 5).addLayer(osm);

// attaching function on map click
map.on('click', onMapClick);

map.on('boxzoomend', function(e) {
	console.log('box zoom end', e);
});

map.on('zoomstart', function(e) {
	console.log('zoom start', e);
})

// Script for adding marker on map click
function onMapClick(e) {

    var geojsonFeature = {
        "type": "Feature",
            "properties": {},
            "geometry": {
                "type": "Point",
                "coordinates": [e.latlng.lat, e.latlng.lng]
        }
    }

    var marker;

    L.geoJson(geojsonFeature, {
        
        pointToLayer: function(feature, latlng){
            
            marker = L.marker(e.latlng, {
                
                title: "Resource Location",
                alt: "Resource Location",
                riseOnHover: true,
                draggable: true,

            }).bindPopup("<input type='button' value='Delete this marker' class='marker-delete-button'/>");

            marker.on("popupopen", onPopupOpen);
       
            return marker;
        }
    }).addTo(map);
}


// Function to handle delete as well as other events on marker popup open
function onPopupOpen() {

    var tempMarker = this;

    //var tempMarkerGeoJSON = this.toGeoJSON();

    //var lID = tempMarker._leaflet_id; // Getting Leaflet ID of this marker

    // To remove marker on click of delete
    $(".marker-delete-button:visible").click(function () {
        map.removeLayer(tempMarker);
    });
}


// getting all the markers at once
function getAllMarkers() {
    
    var allMarkersObjArray = [];//new Array();
    var allMarkersGeoJsonArray = [];//new Array();

    $.each(map._layers, function (ml) {
        //console.log(map._layers)
        if (map._layers[ml].feature) {
            
            allMarkersObjArray.push(this)
                                    allMarkersGeoJsonArray.push(JSON.stringify(this.toGeoJSON()))
        }
    })

    console.log(allMarkersObjArray);
    alert("total Markers : " + allMarkersGeoJsonArray.length + "\n\n" + allMarkersGeoJsonArray + "\n\n Also see your console for object view of this array" );
}

$(".get-markers").on("click", getAllMarkers);
});
html, body, #map {
    width:100%;
    height:96%;
    margin:0;
    padding:0;
}
.get-markers {
    width:100%;
    margin:10px 0;
}
<html>
<head>
<!-- Make sure you put this AFTER Leaflet's CSS -->
 <script src="https://unpkg.com/[email protected]/dist/leaflet.js"
   integrity="sha512-QVftwZFqvtRNi0ZyCtsznlKSWOStnDORoefr1enyq5mVL4tmKB3S/EnC3rRJcxCPavG10IcrVGSmPh6Qw5lwrg=="
   crossorigin=""></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css"
   integrity="sha512-puBpdR0798OZvTTbP4A8Ix/l+A4dHDD0DGqYW6RQ+9jxkRFclaxxQb/SJAWZfWAkuyeQUytO7+7N4QKrDh+drA=="
   crossorigin=""/>
</head>
<body>
<div id="map" data-mode="">
    <input type="hidden" data-map-markers="" value="" name="map-geojson-data" />
</div>
<div>
    <input class="get-markers" type="button" value="Get all the Markers" />
</div>
</body>
</html>
like image 90
sets Avatar answered Sep 28 '22 06:09

sets


Custom code for Leaflet 1.6.0

After import leaflet library:

L.CustomBoxZoom = L.Map.BoxZoom.extend({
  _onMouseUp: function(e) {
    if (e.which !== 1 && e.button !== 1) return
    this._finish()
    if (!this._moved) return
    this._clearDeferredResetState()
    this._resetStateTimeout = setTimeout(L.bind(this._resetState, this), 0)
    var latlng1 = this._map.containerPointToLatLng(this._startPoint)
    var latlng2 = this._map.containerPointToLatLng(this._point)
    var bounds = L.latLngBounds(latlng1, latlng2)
    this._map.fire('boxzoomend', { boxZoomBounds: bounds })
  },
})
L.Map.addInitHook('addHandler', 'customBoxZoom', L.CustomBoxZoom)

Then init your map:

var map = L.map('yourmap', { boxZoom: false, customBoxZoom: true }).setView([0, 0], 0)

And listen to boxzoom event:

map.on('boxzoomend', function(e) {
  console.log(e)
})

=>> OK it just log event object to the console, not zoom anymore!!!

like image 21
Quân Vương Avatar answered Sep 28 '22 07:09

Quân Vương