texas697
texas697

Reputation: 6397

how to calculate distance between 2 sets of lat/lng

I am using a react-native-gmaps module for a tracking app. It is a light package with a few methods exposed.

<RNGMap
ref={'gmap'}
style={{ width: this.state.mapWidth, height: this.state.mapHeight }}
markers={this.state.markers}
zoomLevel={this.state.zoom}
onMapChange={(e) => this._handleMapChange(e) }
center={this.state.center}
onMarkerClick={(e) => this._handleMarkerPress(e) }/>

For every polyline point that is placed on the map the map gets re-centered. (move the map and it bounces back to center) It is following the user. I have added a icon that enables/disables this option. What I would like to do is remind the user that this option is available. I have placed a icon on the right side of the map.

screenshot

I want to use the

onMapChange

method to do this. I want the icon to change colors when the user moves the map.(if the followMe option is set to true).

    _handleMapChange(e) {

    console.log(e)

    if (this.state.isFollowing) {
        this.setState({ followingIconBackground: colors.rgba.mapBlue })
    TimerMixin.setTimeout.call(this, () => {
        this.setState({ followingIconBackground: colors.rgba.mapGrey })
    }, 100)
    }
}

The problem is this method gets triggered every time the map moves. so I need to set a minimum lat/lng distance change to prevent my function triggering every time a polyline point is added to the map. How to I calculate this? The similar questions out there seem to be over complicated for this.

So I assume it would be something like this. But I am not sure how or what to compare

    var oldLat;
var oldLng;
_handleMapChange(e) {

    if (compare old with new  )
    if (this.state.isFollowing) {
        this.setState({ followingIconBackground: colors.rgba.mapBlue })
        TimerMixin.setTimeout.call(this, () => {
            this.setState({ followingIconBackground: colors.rgba.mapGrey })
        }, 100)
    }
    oldLat = e.lat
    oldLng = e.lng
}

Upvotes: 0

Views: 2118

Answers (1)

Mahmal Sami
Mahmal Sami

Reputation: 709

For Advanced geospatial calculus, I use http://turfjs.org/
(can be used server Side and Front Side)

var point1 = {
  "type": "Feature",
  "properties": {},
  "geometry": {
    "type": "Point",
    "coordinates": [-75.343, 39.984]
  }
};
var point2 = {
  "type": "Feature",
  "properties": {},
  "geometry": {
    "type": "Point",
    "coordinates": [-75.534, 39.123]
  }
};
var units = "miles";

var points = {
  "type": "FeatureCollection",
  "features": [point1, point2]
};

//=points

var distance = turf.distance(point1, point2, units);

//=distance

source: http://turfjs.org/docs/#distance

You'll need to create your points as GeoJson, (as described above)

Upvotes: 2

Related Questions