I am creating a Phonegap App (using jQuery and Google Maps API V3) related to travelling and would like to show the user the distance he/she has travelled since starting the app.
Is there any Google function for this? Or can anyone recommend what I can do to get the total distance travelled?
It can be done easily. You have to understand, by using a Google Maps API for jQuery you have all needed tools to do it by yourself.
First, you need to define a time period (lets say 1 minute). We will need it to create a reference point of our movements. Next step is to use phonegap/cordova geolocation API to calculate our position (latitude and longitude):
http://docs.phonegap.com/en/1.0.0/phonegap_geolocation_geolocation.md.html
At this point choose do you want to:
Store a position (latitude and longitude) every 1 minute in some js array
Or do the same thing like in point 1 and also show it on the map with gmap addMarker ability.
At the end you need to calculate a distance. Loop through the position array and use latitude and longitude to calculate a distance between every available point. Here you will find function used for a such calculation (with a js example):
http://www.movable-type.co.uk/scripts/latlong.html
Or you can use Google Maps APi function:
google.maps.geometry.spherical.computeDistanceBetween (latLngA, latLngB);
EDIT:
Here's a working example for you: http://jsfiddle.net/Gajotres/6YpAG/
Code:
$(document).ready(function(){
// Chicago
var coordinateObject= new Object();
coordinateObject.lat = '41.83682786072714';
coordinateObject.lng = '-87.626953125';
geoLocationHandler.addLocation(coordinateObject);
// New York
var coordinateObject= new Object();
coordinateObject.lat = '40.58058466412761';
coordinateObject.lng = '-74.00390625';
geoLocationHandler.addLocation(coordinateObject);
// Toronto
var coordinateObject= new Object();
coordinateObject.lat = '43.70759350405294';
coordinateObject.lng = '-79.365234375';
geoLocationHandler.addLocation(coordinateObject);
var len = geoLocationHandler.arrLocations.length;
for (var i = 0; i < len; i++) {
if(i == 1){
geoLocationHandler.distance += geoLocationHandler.calcDistance(geoLocationHandler.arrLocations[i-1].lat,geoLocationHandler.arrLocations[i-1].lng,geoLocationHandler.arrLocations[i].lat,geoLocationHandler.arrLocations[i].lng);
}
}
alert(geoLocationHandler.distance);
});
var geoLocationHandler = {
arrLocations : [],
distance : 0,
addLocation:function(obj){
geoLocationHandler.arrLocations.push(obj);
},
calcDistance:function(fromLat, fromLng, toLat, toLng) {
return google.maps.geometry.spherical.computeDistanceBetween(new google.maps.LatLng(fromLat, fromLng), new google.maps.LatLng(toLat, toLng));
}
};
Final result is a distance expressed in meters.
Every time you have a new coordination use this to create a new object and add it to the array:
var coordinateObject= new Object();
coordinateObject.lat = '41.83682786072714'; // Change with your latitude
coordinateObject.lng = '-87.626953125'; // Change with your longitude
geoLocationHandler.addLocation(coordinateObject);
Related
This is how i calculate the Distance between my list.
my code is below
public void calc(){
for(int i = 0; i < mSearchResultModelsToGetAppointments.size(); i++){
Location newLocation = new Location("");
newLocation.setLatitude(gpsTracker.getLatitude());
newLocation.setLongitude(gpsTracker.getLongitude());
if(String.valueOf(gpsTracker.getLatitude()).equalsIgnoreCase("0.0") || String.valueOf(gpsTracker.getLongitude()).equalsIgnoreCase("0.0")) {
} else{
Location oldLocation = new Location("");
oldLocation.setLatitude(mSearchResultModelUnderProcess.getLatitude());
oldLocation.setLongitude(mSearchResultModelUnderProcess.getLongitude());
float distanceInMeters = newLocation.distanceTo(oldLocation)/1000;
if(distanceInMeters < 2820){
getAdapter().notifyDataSetChanged();
getAdapter().removeItem(i);
getAdapter().notifyDataSetChanged();
}
}
}
}
This is how i display the location now.
If you do not want use any external library, I would suggest following way.
Create your own custom Location Class with attributes lat and lng, and additionally attribute called distance which measures from your current location till the point. here you can find how to find distance between 2 points
This class should implement Comparable interface and override its compare function. Inside this function, you can create your own sorting logic based on distance
here you can find how to use comparable interface, Let me know if you have still problem
Happy coding
Sorry for not providing any sample code because I don't have any idea about how to do this.
I'm coding an Android application which uses Firebase as the backend.
I'm storing the current current user location to mysl db using the fusedlocationapi.
Now, when a user is logged into the application, he/she is given a option to show only the list of user around a radius of 25km (let's assume as an example). Can any one guide me with this feature please.
I don.t wanna do this on client side ...is there any way to so it using mysql
You can use Google Maps Android API utility library
public class DistanceHelper {
private static final Double RADIUS = 25000.0;
public static double getDistance(LatLng user1, LatLng user2){
double distance = SphericalUtil.computeDistanceBetween(user1, user2);
return distance;
}
public static Double getRadius(){
return RADIUS;
}
public static String formatNumber(double distance) {
String unit = "m";
if (distance < 1) {
distance *= 1000;
unit = "mm";
} else if (distance > 1000) {
distance /= 1000;
unit = "km";
}
return String.format("%4.3f%s", distance, unit);
}
}
LatLng user1 = new LatLng(currentUser.getLatitude(), currentUser.getLongitude());
LatLng user2 = new LatLng(otherUser.getLatitude(), otherUser.getLongitude());
Double distance = DistanceHelper.getDistance(user1, user2);
if (distance <= DistanceHelper.getRadius()) {
//code here
}
I store the users' latitude and longitude in FB database using GPS and LocationManager. put the calculation inside your ChildEventListener to retrieve get users inside 25km radius.
However I think this implementation is wrong because the calculations are done on client side so what if you have million or billion of users then you have to compute each one by one on client's device which might cause very slow performance of your app.
I am using android Here-sdk. I got total distance of perticular route from MapRoute object. So now i want to get arrival/travel time of perticular route.
Below is the code for distance. what would i do for get time from MapRoute object. Thanks!
for(int i = list_routes.size() ; i > 0 ; i--)
{
MapRoute mapRoute = new MapRoute(list_routes.get(i-1).getRoute());
mapRoute.setColor(color_array.get(i-1));
mapRoute.setTrafficEnabled(true);
// here i got total distance
int distance = mapRoute.getRoute().getLength();
m_map.addMapObject(mapRoute);
}
You can do it like that:
int timeInSeconds = mapRoute.getRoute().getTta(x, y).getDuration();
where x is TrafficPenaltyMode and y is subleg number. You can check the details in the documentation.
The documentaion link change use this instead documentation
the getTTa method is deprecated now, use
Route.getTtaIncludingTraffic(int subleg)
or
Route.getTtaExcludingTraffic(int subleg)
if you want the travel time for the whole route use this value
Route.WHOLE_ROUTE
example:
int timeInSeconds = route.getTtaExcludingTraffic(Route.WHOLE_ROUTE).getDuration();
I would like to search places between two given distances, using GeoPoints. Using the currently api, I think I could make something like this pseudo algorithm:
query.whereWithinKilometers("directions", GlobalData.ownerGeoPoint, MAXIMUM distance);
MINUS
query.whereWithinKilometers("directions", GlobalData.ownerGeoPoint, MINIMUM distance);
How can I translate to real code?
Finally I found a way to do it with a parse query.
// Do not want locations further than maxDistance
ParseQuery query = ParseQuery.getQuery("MyData");
query.whereWithinKilometers("location", userGeoPoint, maxDistance);
// Do not want locations closer than minDistance
ParseQuery<ParseObject> innerQuery = ParseQuery.getQuery("MyData");
innerQuery.whereWithinKilometers("location", userGeoPoint, minDistance);
query.whereDoesNotMatchKeyInQuery("objectId", "objectId", innerQuery);
Likely you'll have to pull in everything within the maximum distance from Parse to your app, then inside your app filter out anything that is closer than the minimum.
Thankfully Parse includes some distance measuring as part of PFGeoPoint. Check out the three methods here.
distanceInRadiansTo:
distanceInMilesTo:
distanceInKilometersTo:
So your pseudocode is:
(After you get back everything within the outer radius)
Make a new array (var) called finalList
For i = 0; i < objects.count; i++ {
var gp: PFGeoPoint = objects[i]
if gp.distanceInMilesTo:originalGeoPoint >= minimumRadiusInMiles {
finalList.push(gp)
}
}
I'm using MapQuest (since Google Map API will be down in september) and I'd like to add a point at an exact coordinates position.
I've created a movieClip named geoPoint and traced a circle in it.
Now, I've managed to display the coordinates in a text field like that :
if (Geolocation.isSupported){
var my_geo:Geolocation = new Geolocation();
my_geo.addEventListener(GeolocationEvent.UPDATE, onGeoUpdate);
my_geo.setRequestedUpdateInterval(50);
var my_txt:TextField = new TextField();
my_txt.wordWrap=true;
addChild(my_txt);
}
function onGeoUpdate(e:GeolocationEvent):void{
my_txt.text = "My Latitude is "+e.latitude+" and my Longitude is "+e.longitude;
}
Now is it possible to add my movieClip at the e.latitude and e.longitude point ?
I've tried :
var geo:MovieClip;
geo = new geoPoint;
addChild(geo(new LatLng(e.latitude, e.longitude)));
but it doesn't work.
Someone knows how can I do it ?
Thanks !
It should be
geo = new geoPoint();
You should also probably figure how to translate latitude and longitude to x and y coordinates, because I'm doubtful the next line will work. You're calling a MovieClip constructor that takes a LatLng argument.
For what you need to achive, you may have to use a class provided by the MapQuest Api, like PolygonOverlay or CircleOverlay. There is an example here under "Shape Collections" http://developer.mapquest.com/content/as3/v7/7.0.6_MQ/samples/samplesexplorer/index.html#