Skip to content

Commit

Permalink
Add setBounds() method
Browse files Browse the repository at this point in the history
  • Loading branch information
heyman committed Nov 21, 2023
1 parent 0c15fa6 commit af4bab6
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 2 deletions.
10 changes: 8 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ but doesn't support keeping the aspect ratio.
var areaSelect = L.areaSelect({width:200, height:300, minWidth:40, minHeight:40, minHorizontalSpacing:40, minVerticalSpacing:100, keepAspectRatio:false});
areaSelect.addTo(map);

// Read the bouding box
// Read the bounding box
var bounds = areaSelect.getBounds();

// Get a callback when the bounds change
Expand All @@ -30,12 +30,18 @@ but doesn't support keeping the aspect ratio.
//areaSelect.remove();
```

**You can also make it keep the aspect ratio:**
### To make it keep the aspect ratio:

```javascript
var areaSelect = L.areaSelect({width:200, height:300, keepAspectRatio:true});
```

### To set the selected area (not compatible with `keepAspectRatio:true`):

```javascript
areaSelect.setBounds([{lat:59.2272559, lng:17.7606917}, {lat:59.4402838, lng:18.2000673}]);
```

## See it in action

Check out the [bundled example](http://heyman.github.io/leaflet-areaselect/example/).
Expand Down
21 changes: 21 additions & 0 deletions src/leaflet-areaselect.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,28 @@ L.AreaSelect = L.Class.extend({
return new L.LatLngBounds(sw, ne);
},

/**
* Adjust the map bounds to fit the desired selection, and resize the selection to match the bounds parameter.
*
* Note that the actual bounds after running this function may not match the bounds parameter exactly, since
* we're converting between pixels and latlng coordinates.
*
* This method is not compatible with the keepAspectRatio option.
*/
setBounds: function(bounds) {
bounds = L.latLngBounds(bounds);
this.map.fitBounds(bounds, {
animate: false,
paddingTopLeft: [this.options.minHorizontalSpacing/2, this.options.minVerticalSpacing/2],
paddingBottomRight:[this.options.minHorizontalSpacing/2, this.options.minVerticalSpacing/2],
});

let nwPx = this.map.latLngToLayerPoint(bounds.getNorthWest());
let sePx = this.map.latLngToLayerPoint(bounds.getSouthEast());
this.setDimensions({
width: sePx.x - nwPx.x,
height: sePx.y - nwPx.y,
})
},

remove: function() {
Expand Down

0 comments on commit af4bab6

Please sign in to comment.