Home > Net >  How to check if coordinates are contained in current viewport of map?
How to check if coordinates are contained in current viewport of map?

Time:06-20

I have a route (array of coordinates) displayed on the map (react-native-maps). I want to check if the coordinates of the route are in the viewport to trigger some subsequent operations (or not).

  const route = [
        {
            latitude: 41.38145,
            longitude: 2.17182,
        },
        {
            latitude: 41.38154,
            longitude: 2.17203,
        },
        {
            latitude: 41.38155,
            longitude: 2.17205,
        },
    ];

const MapDisplay = () => {
    const onRegionChange = (region) => {
     //searched function
        routeIsInViewport(region, route);
    };

    return <MapView onRegionChange={onRegionChange} />;
};

CodePudding user response:

You can find the min and max latitude/longitude in the completion for the region, then compare the value with the array of the route to find if it is within..

const onRegionChange = (region) => {
     let lat_min = region.latitude - (region.latitudeDelta / 2);
     let lat_max = region.latitude   (region.latitudeDelta / 2);

     let lng_min = region.longitude - (region.longitudeDelta / 2);
     let lng_max = region.longitude   (region.longitudeDelta / 2);

     routes.map((route)=>{
        if((route.latitude>=lat_min && route.latitude<=lat_max) && (route.longitude>=lng_min && route.longitude<=lng_max)){
             //Within region do your stuff
        }
     })
};

Hope it helps, cheers.

  • Related