zoom into boundaries of leaflet polygon

215 views
Skip to first unread message

Ailis

unread,
Apr 16, 2017, 1:19:44 PM4/16/17
to Leaflet
Hi all,
fairly leaflet novice. I'm trying to put a polygon on my map that is highlighted when the user hovers over it, and when they click it, the map will zoom into the boundaries of the polygon. However, I've tried a bunch of different methods to get the map to zoom(some from this forum) and just can't get it to work. 
I've already coded the polygon so that when a user mouses over it, a different polygon of the same shape shows up with a stroke. This also is a little glitchy, so if there's a better method for making a change on mouseover please let me know!

The event listener for clicking the polygon is at the bottom. I've tried a bunch of different syntax including: 

// the original polygon is the one listening now (maybe they should both have event listeners?)
dtPolygon.addEventListener("click", function(){
    dealMap.fitBounds(polygonPoints);
;});

dtPolygon.addEventListener("click", function(){
    dealMap.fitBounds(dtPolygon.getbounds());
;});

dtPolygon.addEventListener("click", function(){
    dealMap.fitBounds(polygon2.getbounds());
;});

// and just other ideas for what could work, switching out the dtPolygon & polygon 2, which is the "hover" polygon that shows up.

var p1 = new L.LatLng(35.600449, -82.562839),
    p2 = new L.LatLng(35.603380, -82.557517),
    p3 = new L.LatLng(35.602996, -82.546703),
    p4 = new L.LatLng(35.598290, -82.544061),
    p5 = new L.LatLng(35.591574, -82.541886),
    p6 = new L.LatLng(35.588481, -82.543066),
    p7 = new L.LatLng(35.588481, -82.543066),
    p8 = new L.LatLng(35.588073, -82.552910),
    p9 = new L.LatLng(35.588828, -82.561375),
    p10 = new L.LatLng(35.595842, -82.563006),
    polygonPoints = [p1, p2, p3, p4, p5, p6, p7, p8, p9, p10];

var polygonOptions = {
stroke: false, 
                 fillColor: 'green', 
                 fillOpacity: 0.5
};
         
var dtPolygon = new L.Polygon(polygonPoints, polygonOptions).addTo(dealMap);

var polygon2 = new L.Polygon(polygonPoints, {color: 'green', stroke: true});


dtPolygon.addEventListener("mouseover", function(){
    polygon2.addTo(dealMap);
;});

dtPolygon.addEventListener("mouseout", function(){
    polygon2.remove(dealMap);
;});



polygon2.addEventListener("click", function(){
    dealMap.fitBounds(polygonPoints);
;});



Matt Travis

unread,
Apr 19, 2017, 11:19:57 AM4/19/17
to Leaflet
What happens if you use getBounds in the last event listener?

polygon2.addEventListener("click", function(){
    dealMap.fitBounds(polygonPoints.getBounds());
;});
Reply all
Reply to author
Forward
0 new messages