I am wondering if there is a way to change the colour of a polygon got from a geojson file only if the users/browser location is within that polygon if so is there any example or working code that cpild be shared

No code But some pseudocode to give the general idea:

Function locationWithinPolygon (e) {
if (browserlocation within GeoJSONPolygonBoundaries){
pan to feature
Change colour of polygon to white
popUpMessage "Your are within" + polygonName }
else {
function OnLocationError{ alert(e.message); }
map.on("location error" + OnLocationError)


You can use the turf function booleanContains:

<script src="https://cdn.jsdelivr.net/npm/@turf/turf@5.1.6/turf.min.js"></script>

var poly = L.polygon([[22.29227, 114.20847],[32.28227, 110.24847],[42.08227, 114.19847]]).addTo(map)

function onLocationFound(e) {
    var marker = L.marker(e.latlng).addTo(map)

    var contains = turf.booleanContains(poly.toGeoJSON(),marker.toGeoJSON())
      poly.setStyle({color: 'green'})
        poly.setStyle({color: 'red'})
    // fit the map to the marker AND polygon
    var bounds = L.latLngBounds();
map.on('locationfound', onLocationFound);

function onLocationError(e) {
map.on('locationerror', onLocationError);


Edit: GeoJSON

With Multi-Polygons you can use turf.booleanContains use instead turf.booleanPointInPolygon:

geoJsonGroup.eachLayer((layer) => {
          var contains = turf.booleanPointInPolygon(marker.toGeoJSON(), layer.toGeoJSON())
          if (contains) {
            layer.feature.properties.polyWithLocation = true;

Instead of calling .setStyle we add a flag to the feature properties, so the style still applied when .resetStyle() is called.

function highlightstyle(feature) {
        if (feature.properties.polyWithLocation) {
          return {
            weight: 2,
            opacity: 1,
            color: 'white',
            dashArray: '3',
            fillOpacity: 0.4,
            fillColor: 'green'
        } else {
          return {
            weight: 2,
            opacity: 1,
            color: 'gray',
            dashArray: '3',
            fillOpacity: 0.0

You had a few mistakes in your code, I fixed it: https://jsfiddle.net/falkedesign/xgr9opce/

  • Looks valid but when reading from a geoJSON file could this be done to see if a user location is within one of multiple polygons from the file, such as count data? Here is a live version of what I am working on so could I do this within my county data> ces-web2.southwales.ac.uk/students/18018424/leaflet2.htm – WMTS Feb 12 at 13:41
  • 1
    @WMTS I updated my answer, please don't forgett ot accept this answer as correct – Falke Design Feb 12 at 14:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.