javascript 确定点是否在GEOJSON多边形内?

2ul0zpep  于 2023-05-16  发布在  Java
关注(0)|答案(1)|浏览(226)

在我将KMZ转换为KML然后转换为JSON文件后,我得到了以下结构:

{
  "type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      "geometry": {
        "type": "Polygon",
        "coordinates": [
          [
            [lon1, lat1],
            [lon2, lat2],
            [lon3, lat3],
            ...
          ]
        ]
      },
      "properties": {
        "property1": "value1",
        "property2": "value2",
        ...
      }
    },

在我的脑海中找到GPS点,我应该迭代坐标点并检查点是否在GEOJSON多边形内,所以我使用turf.js库中的代码

// define the URL for the GeoJSON data
const url = 'path/geojson.json';

// define the GPS point to check
const pointToCheck = turf.point([-6.542, 34.224]);

// fetch the GeoJSON data
fetch(url)
  .then(response => response.json())
  .then(myJSON => {
    // loop through each feature in the GeoJSON data
    myJSON.features.forEach(feature => {
      // get the polygon geometry for this feature
      const polygon = feature.geometry;
      
      // check if the GPS point is inside the polygon geometry
      const isInside = turf.booleanPointInPolygon(pointToCheck, polygon);
      
      // if the GPS point is inside the polygon, log the feature's properties
      if (isInside) {
        console.log(feature.properties);
        
        // loop through each set of coordinates in the polygon
        polygon.coordinates.forEach(coordinates => {
          coordinates.forEach(coordinate => {
            console.log(coordinate);
          });
        });
      }
    }); 
  })
  .catch(error => {
    console.error('Error fetching GeoJSON data:', error);
  });

UPDATE我正确上传JSON文件
我的问题是,因为我从来没有使用过Turf.js,所以这个函数booleanPointInPolygon(pointToCheck, polygon);是否可以正确地检查我的点是否在这个几何体内
我试图从JSON中获取数据,如果我给予他的点在该GEOJSON文件中存在的几何图形内

vuktfyat

vuktfyat1#

只使用Google Maps JavaScript API v3几何库(而不是turf)的一个选项是在geometry library中使用containsLocation方法:

// define the GPS point to check
const pointToCheck = new google.maps.LatLng(-30.5581449, 138.423925)
const marker = new google.maps.Marker({map:map, position: pointToCheck})
// fetch the GeoJSON data
fetch(url)
  .then(response => response.json())
  .then(myJSON => {
    // loop through each feature in the GeoJSON data
    myJSON.features.forEach(feature => {
      // get the polygon geometry for this feature
      const polygon = feature.geometry;
      const gmPaths = [];
      for (var j=0; j<polygon.coordinates.length; j++) {
        gmPaths.push([]);
        for (var i=0; i<polygon.coordinates[j].length; i++) {
          gmPaths[j].push(new google.maps.LatLng(polygon.coordinates[j][i][1],polygon.coordinates[j][i][0]))
        }
      }
      const gmPolygon = new google.maps.Polygon({
      map:map,
      paths: gmPaths
      })
      // check if the GPS point is inside the polygon geometry
      const isInside = google.maps.geometry.poly.containsLocation(pointToCheck, gmPolygon)
      
      // if the GPS point is inside the polygon, log the feature's properties
      console.log("isInside="+isInside);
      if (isInside) {
        console.log("properties="+JSON.stringify(feature.properties));
        
        // loop through each set of coordinates in the polygon
        polygon.coordinates.forEach(coordinates => {
          coordinates.forEach(coordinate => {
            console.log(coordinate);
          });
        });
      }
    }); 
  })
  .catch(error => {
    console.error('Error fetching GeoJSON data:', error);
  });

proof of concept fiddle

代码片段:

let map;

function initMap() {
  map = new google.maps.Map(document.getElementById("map"), {
    zoom: 4,
    center: { lat: -28, lng: 137 },
  });
  // Load GeoJSON.
  // define the URL for the GeoJSON data
const url = "https://storage.googleapis.com/maps-devrel/google.json"
// define the GPS point to check
const pointToCheck = new google.maps.LatLng(-30.5581449, 138.423925)
const marker = new google.maps.Marker({map:map, position: pointToCheck})
// fetch the GeoJSON data
fetch(url)
  .then(response => response.json())
  .then(myJSON => {
    // loop through each feature in the GeoJSON data
    myJSON.features.forEach(feature => {
      // get the polygon geometry for this feature
      const polygon = feature.geometry;
      const gmPaths = [];
      for (var j=0; j<polygon.coordinates.length; j++) {
        gmPaths.push([]);
        for (var i=0; i<polygon.coordinates[j].length; i++) {
          gmPaths[j].push(new google.maps.LatLng(polygon.coordinates[j][i][1],polygon.coordinates[j][i][0]))
        }
      }
      const gmPolygon = new google.maps.Polygon({
      map:map,
      paths: gmPaths
      })
      // check if the GPS point is inside the polygon geometry
      const isInside = google.maps.geometry.poly.containsLocation(pointToCheck, gmPolygon)
      
      // if the GPS point is inside the polygon, log the feature's properties
      console.log("isInside="+isInside);
      if (isInside) {
        console.log("properties="+JSON.stringify(feature.properties));
        
        // loop through each set of coordinates in the polygon
        polygon.coordinates.forEach(coordinates => {
          coordinates.forEach(coordinate => {
            console.log(coordinate);
          });
        });
      }
    }); 
  })
  .catch(error => {
    console.error('Error fetching GeoJSON data:', error);
  });
}

window.initMap = initMap;
#map {
  height: 100%;
}

html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}

#info-box {
  background-color: white;
  border: 1px solid black;
  bottom: 30px;
  height: 20px;
  padding: 10px;
  position: absolute;
  left: 30px;
}
<!DOCTYPE html>
<html>
  <head>
    <title>Data Layer: Event Handling</title>
    <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
    <!-- jsFiddle will insert css and js -->
  </head>
  <body>
    <div id="map"></div>
    <div id="info-box">?</div>

    <!-- 
      The `defer` attribute causes the callback to execute after the full HTML
      document has been parsed. For non-blocking uses, avoiding race conditions,
      and consistent behavior across browsers, consider loading using Promises.
      See https://developers.google.com/maps/documentation/javascript/load-maps-js-api
      for more information.
      -->
    <script
      src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDGhGk3DTCkjF1EUxpMm5ypFoQ-ecrS2gY&callback=initMap&v=weekly&libraries=geometry"
      defer
    ></script>
  </body>
</html>

相关问题