UNPKG

ojp-sdk-legacy

Version:

OJP (Open Journey Planner) Javascript SDK (legacy version)

70 lines (69 loc) 2.57 kB
export class GeoPosition { constructor(longitude, latitude) { this.longitude = parseFloat(longitude.toFixed(6)); this.latitude = parseFloat(latitude.toFixed(6)); this.properties = null; } static initWithStringCoords(longitudeS, latitudeS) { if (longitudeS === null || latitudeS === null) { return null; } const longitude = parseFloat(longitudeS); const latitude = parseFloat(latitudeS); if (longitude === 0 || latitude === 0) { return null; } const geoPosition = new GeoPosition(longitude, latitude); return geoPosition; } static initWithLocationTreeNode(locationTreeNode) { const longitudeS = locationTreeNode.findTextFromChildNamed('GeoPosition/siri:Longitude'); const latitudeS = locationTreeNode.findTextFromChildNamed('GeoPosition/siri:Latitude'); const geoPosition = GeoPosition.initWithStringCoords(longitudeS, latitudeS); return geoPosition; } static initWithFeature(feature) { if (feature.geometry.type !== 'Point') { return null; } const lngLatAr = feature.geometry.coordinates; const longitude = lngLatAr[0]; const latitude = lngLatAr[1]; const geoPosition = new GeoPosition(longitude, latitude); geoPosition.properties = feature.properties; return geoPosition; } asLngLat() { const lnglat = [ this.longitude, this.latitude, ]; return lnglat; } asLatLngString(roundCoords = true) { let s = ''; if (roundCoords) { s = this.latitude.toFixed(6) + ',' + this.longitude.toFixed(6); } else { s = this.latitude + ',' + this.longitude; } return s; } asPosition() { return [this.longitude, this.latitude]; } // From https://stackoverflow.com/a/27943 distanceFrom(pointB) { const R = 6371; // Radius of the earth in km const dLat = (pointB.latitude - this.latitude) * Math.PI / 180; const dLon = (pointB.longitude - this.longitude) * Math.PI / 180; const a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(this.latitude * Math.PI / 180) * Math.cos(pointB.latitude * Math.PI / 180) * Math.sin(dLon / 2) * Math.sin(dLon / 2); const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); const d = R * c; const dMeters = Math.round(d * 1000); return dMeters; } }