I have locations stored in mongodb that look like this in mongoose schema:
location: {
type: [Number],
index: '2d'
}
And on web client I'm using google maps api with custom radius resizer:
On each drag I'm making request with radius value that is calculated on client. Radius is the distance between pink arrow marker and center coordinates:
function metersToMiles (meters) {
return meters * 0.000621371192;
}
google.maps.event.addListener(this.sizer, 'dragend', () => {
const radius = this.circle.getRadius();
const radiusValue = Math.round(metersToMiles(radius) * 10) / 10; // convert to tenths (this is shown on UI as well)
this.props.onRadiusChange(radiusValue); // it's a react component
});
In mongodb request I'm using $nearSphere with radius in $maxDistance:
function milesToRadian(miles){
const earthRadiusInMiles = 3963.2;
return parseFloat(miles) / earthRadiusInMiles;
}
const { radius, lat, lon } = req.query;
const coords = (lat && lon) ? [lat, lon] : ukCoordinates;
const radians = milesToRadian(radius);
console.log('%s, %s, %s', radius, coords, radians);
// what I receive: 1.6, 0.00040371417036737993, [ 51.507351, -0.127758 ]
// ...
{
$nearSphere: coords,
$maxDistance: radians
}
However if you take a look on the gif image you'll see that there's some inaccuracy in results. For now I'm stucked with it, could you suggest what is the problem?
So the problem was really funny but still tricky. I've found out that in MongoDB you need to store coordinate pairs as [longitude, latitude] and not vice versa:
location: {
type: [Number], // longitude, latitude
index: '2d'
}
But in Google Maps SDK the order is different:
new google.maps.LatLng(lat, lng);
So to fix my problem I've needed to store coordinates in right order in MongoDB.
Related
I want to calculate distance from a collection of geo coordinates. I have converted this to a GPX file and I am able to use in HERE Maps to calculate distance.
Now, I want to use this in Google Maps as per my customer requirement. Is there any option in Google Maps which accepts GPX file and return distance ? I have seen distancematrix option and believe this is in different format.
There are some parts here. The calculation based on Google Maps docs.
Notice that if you need only to calculate the distances, you don't need even google maps api. The calculation is based on the coordinates only.
Parse GPX file
GPX is basically an xml as well as html. So After you parse the content of the file using window.DOMParser().parseFromString(str, "text/xml")); you can use the DOM API (such as querySelector, querySelectorAll etc.) to retrieve all the trkpt element and extract their lat and lon values.
const coords = Array.from(xml.querySelectorAll("trkpt")).map(
element =>
new google.maps.LatLng(
Number(element.getAttribute("lat")),
Number(element.getAttribute("lon"))
)
);
I used google.maps.LatLng but you can store it in a plain object if you don't need it to interact with your map.
Calculate the distances
Iterate over the coordinates array and measure from one point to another.
function haversine_distance(coord1, coord2) {
const R = 3958.8; // Radius of the Earth in miles
const rlat1 = coord1.lat() * (Math.PI/180); // Convert degrees to radians
const rlat2 = coord2.lat() * (Math.PI/180); // Convert degrees to radians
const difflat = rlat2-rlat1; // Radian difference (latitudes)
const difflon = (coord2.lng()-coord1.lng()) * (Math.PI/180); // Radian difference (longitudes)
const d = 2 * R * Math.asin(Math.sqrt(Math.sin(difflat/2)*Math.sin(difflat/2)+Math.cos(rlat1)*Math.cos(rlat2)*Math.sin(difflon/2)*Math.sin(difflon/2)));
return d;
}
Then you can the function to build the distances array
const distances = coords.reduce((old, ne, index, original) => {
if (index > 0) {
old.push(haversine_distance(ne, original[index - 1]));
}
return old;
}, []);
https://codesandbox.io/s/elegant-turing-tvhu1?file=/index.html
I'm developing a job board type website for a client that has filters for the jobs posted. This website is built off of Wordpress and using the Ajax Load More plugin to dynamically populate the jobs. I want to have a filter that a user can enter their address and the closest jobs to that entered address would populate.
I currently have it set up to grab the latitude and longitude of each job posted, as well as, the latitude and longitude of the address when the user enters it, using the Google Maps API. What I can't figure out his how to correlate the two and have Ajax Load More populate the jobs with the closest lat/long to the entered address?
First, create an array that contains the lat/lng's of the job posted. Here's an example:
var job_locs = [ //job locations array
{lat:59.611975, lng:16.547017},//within radius
{lat:59.612186, lng:16.544901},//within radius
{lat:59.614412, lng:16.538992},//within radius
{lat:59.615677, lng:16.546703},//within radius
{lat:59.618794, lng:16.545480},//within radius
{lat:59.622650, lng:16.558984},//outside radius
{lat:59.615612, lng:16.555962},//outside radius
{lat:59.610812, lng:16.549959},//outside radius
{lat:59.608804, lng:16.541045},//outside radius
{lat:59.608084, lng:16.537515},//outside radius
];
As you can see there, I have provided 5 within the 500 meter radius of the user and another 5 outside the radius. Here's the user's location:
var user = { lat: 59.615911, lng: 16.544232 };
Now you just have to loop through the array of job locations and check if they are within the radius. To do this, there is a post about this here in SO: Check if a latitude and longitude is within a circle google maps
if you check the accepted answer (credits to Guffa), he used this function to check if the point is within the radius:
function arePointsNear(checkPoint, centerPoint, km) { // credits to user:69083
var ky = 40000 / 360;
var kx = Math.cos(Math.PI * centerPoint.lat / 180.0) * ky;
var dx = Math.abs(centerPoint.lng - checkPoint.lng) * kx;
var dy = Math.abs(centerPoint.lat - checkPoint.lat) * ky;
return Math.sqrt(dx * dx + dy * dy) <= km;
}
Now we use this function in a loop:
job_locs.forEach(function(locs){
var n = arePointsNear(user, locs, 0.5); //0.5km = 500meters
if(n){
marker = new google.maps.Marker({
map: map,
position: locs,
label: {
text:"I", //marking all jobs inside radius with I
color:"white"
}
});
}else{ //remove this to see only the locations within radius
marker = new google.maps.Marker({
map: map,
position: locs,
label: {
text:"O", //marking all jobs outside radius with O
color:"white"
}
});
}
});
Note: This displays all the nearby locations from the list within the
provided radius. If there are no location found within the radius,
there will be no result. Also, please read the source of
arePointsNear function,
for the limitation of this function.
Here is a working sample in JS Bin: click me!
What You Have
Latitude/Longitude of each job
Latitude/Longitude of user's address
What You Want
List of job post displaying by nearest location
Approach
Calculate the distance using formula in this page
Load list of jobs by the order of distance calculated
I am working on something to blacklist unwanted locations with the location service. Here is my current code:
How can I implement a blacklist feature?
if (navigator.geolocation) {
// Locate position
navigator.geolocation.getCurrentPosition(displayPosition, errorFunction);
} else {
alert('Your device location is not approved.');
}
// Success callback function
function displayPosition(pos) {
var mylat = pos.coords.latitude;
var mylong = pos.coords.longitude;
var thediv = document.getElementById('locationinfo');
alert('Your HWID is compliant of ProtoProt regulations.');
}
function errorFunction(pos) {
alert('Error: (PROTOPROT_POS_DENIED). We only use your HWID for checking compliance. Enable location to enter.');
}
Maintain a list of locations given by two points w,y.
Each w,y represent the two opposite points of a w,x,y,z square which represents the blacklisted location.
Each point has longitude and latitude coordinates, so w = [long, lat] and y = [long, lat]
With those, you can rebuild all the [long, lat] of all the w,x,y,z corners of your square, thus representing the blacklisted area.
Now, it's rather easy to know the boundaries of forbidden location: any point [long, lat] which is within the square is blacklisted.
You can store those values within a Javascript Object (a dictionary) which can be stored in a distinct ".js" file. JSON representation could look like:
blacklisted_areas = {
'area 51' : [w, y], // Replace w y with the floats of long and lat
'pink unicorn zoo' : [w, y], // same
// etc.
};
Access:
long = blacklisted_area['area 51'][0]
I have a list with 50 items:
var mylocations = [{'id':'A', 'loc':[-21,2]},...,];
How can I in leaflet or JavaScript most efficiently make it such that if I accept an input of a specific location [<longitude>,<latitude>], a radius (e.g. 50 miles)... I can get all of the "mylocations" that fall within that circle?
Using external libraries is fine.
Leaflet's L.LatLng objects include a distanceTo method:
Returns the distance (in meters) to the given LatLng calculated using the Haversine formula.
http://leafletjs.com/reference.html#latlng-distanceto
var inRange = [], latlng_a = new L.LatLng(0, 0), latlng_b;
locations.forEach(function (location) {
latlng_b_ = new L.LatLng(location.pos[0], location.pos[1]);
if (latlng_a.distanceTo(latlng_b) < 80.4672) {
inRange.push(location);
}
});
What i have done so far:
i'm developing an application where i have to display more than(50K) points/Markers on the Navteq map divided into different segments.
for example: if i have 50K points i will divide all points into different segments.
if i divide 50K points into 50 segments each segment would have 1000 points (may not be 50 segments , it may depend).
right now it is working but it takes long time and hangs to render all the points on the MAP.so that i would like to perform segmentation displaying to display only few points with clustering.
so that i can get an idea of how the segment will look like.
but the problem here is i should only perform the clustering based on the segments.otherwise points from different segments willbe mixed together and displayed
as single unit and that conveys the wrong information to the user.
so here my question is: is it possible to perform the clustering based on the segment. so that only points from same segment will be clustered.
Note: if this is not possible, i would like to use Latest version of here-maps 2.5.3 (Asynchronous) may reduce some time while loading, so that i would like to use indexing functionality also while rendering the points
to improve the rendering time using nokia.maps.clustering.Index class.
i studied that indexing would reduce the time while rendering the points/markers on map. does it help in my case? could anybody please suggest how to perform indexing ?
This is the code with which i'm displaying points on map:
function displayAllLightPoints(arrLightPointCoordinats, totalLightPoints,
selectedSegmentId, totalSegmentsCount,segmentColorcode)
{
var MyTheme1 = function () {
};
segmentColorcode = segmentColorcode.substring(2,segmentColorcode.length-1);
MyTheme1.prototype.getNoisePresentation = function (dataPoint) {
var markerLightPoint = new nokia.maps.map.Marker(dataPoint, {
icon: new nokia.maps.gfx.BitmapImage("..//Images//Lightpoint//" +
segmentColorcode + ".png"),
anchor: {
x: 12,
y: 12
}
});
return markerLightPoint;
};
MyTheme1.prototype.getClusterPresentation = function (data) {
var markerLightPoint = new
nokia.maps.map.StandardMarker(data.getBounds().getCenter(), {
icon: new nokia.maps.gfx.BitmapImage("..//Images//
Segment/" + segmentColorcode + ".png", null, 66, 65),
text: data.getSize(),
zIndex: 2,
anchor: {
x: 12,
y: 12
}
});
return markerLightPoint;
};
var ClusterProvider = nokia.maps.clustering.ClusterProvider,
theme = new MyTheme1(),
clusterProvider = new ClusterProvider(map, {
eps: 0.00000000001,
minPts: 1000000,
strategy: nokia.maps.clustering.ClusterProvider.
STRATEGY_DENSITY_BASED,
theme: theme,
dataPoints: []
});
var lightpointsDataSet1 = new Array();
for (var i = 0; i < totalLightPoints; i++) {
lightpointsDataSet1[i] = { latitude: arrLightPointCoordinats[i][0],
longitude: arrLightPointCoordinats[i][1], title:
'LightPoint ' + (i + 1) };
}
clusterProvider.addAll(lightpointsDataSet1);
clusterProvider.cluster();
}
To deal with a very large (50K+) data set , I would do all the heavy number crunching server side and send over a new JSON response whenever the map is updated. Something like the HTML page described here
The key section of the code is the ZoomObserver:
var zoomObserver = function (obj, key, newValue, oldValue) {
zoom = newValue;
if (zoom < 7)
{ zoom = 7;}
if (zoom > 16)
{ zoom = 16;}
// Define the XML filename to read that contains the marker data
placeMarkersOnMaps('http://api.maps.nokia.com/downloads/java-me/cluster/'+ zoom + '.xml'
+ '?lat1=' + map.getViewBounds().topLeft.latitude
+ '&lng1='+ map.getViewBounds().topLeft.longitude
+ '&lat2='+ map.getViewBounds().bottomRight.latitude
+ '&lng2='+ map.getViewBounds().bottomRight.longitude);
};
map.addObserver("zoomLevel", zoomObserver );
Where the REST service returns a "well-known" data format which can be used to add markers and clusters to the map.
Now assuming you have two massive data sets you could make two requests to different endpoints, or somehow distinguish which cluster of data belongs to which so that you would just be returning information of the form:
{latitude':51.761,'longitude':14.33128,'value':102091},
i.e. using the DataPoint standard (which means you could use a heat map as well.
Of course, what I'm not showing here is the back-end functionality to cluster in the first place - but this leaves the client (and the API) to do what it does best displaying data, not number crunching.