Google Maps API (JS): check if I reached my destination - javascript

I'm developing HTML5 web-app for iPad that uses Google Maps API. This API is new for me, I have searched answers for many questions related to it. Markers, info windows, routes, geolocation, street view. The most useful information about that all was found in official documentation:
https://developers.google.com/maps/documentation/javascript/3.exp/reference?hl=ru
However, I still cannot find a solution to one (maybe, simple) problem. For example, I've created a new map instance and one marker (destination), started watching for my position (GEO Location) and drew a route to the location of this marker. How can I check when I will reach the destination? I've looked for appropriate events of DirectionsService, DirectionsRenderer and etc. but with no results. Also, I found the same topic on this website, but it is about Android development, not JS (Android: How to check that whether i reach/near my Destination?).
Being hopeless, I invented my own solution, but it seems not to work properly (I have not fully tested it yet, I'll do it in the next few days). I thought if I would compare lat&lng of my current position with lat&lng of destination - then I could catch the moment when destination is reached:
if (myPosition.lat() == dest.marker.position.lat() && myPosition.lng() == dest.marker.position.lng()) {
alert('You have arrived!');
}
This code executes in successful watch position callback of navigator.geolocation.watchPosition
Do you have any ideas?

LatLng's are values with a high accuracy, you can't expect that the positions of boths markers will match exactly.
Add a tolerance:
//tolerance 50 meters
//requires the geometry-library
if(google.maps.geometry.spherical
.computeDistanceBetween(myPosition,dest.marker.position)<50){
alert('You have arrived!');
}

I don't think it's a good idea to make a home made solution, since maps API can do quit everything.
Using Google Maps API to get travel time data

For Android Studio users:
Get object of currentLocation and destinationLocation
Location currentLocation; // use fusedLocationProviderService
Location destinationLocation = new Location(""); // set Lat and Long
destinationLocation.setLatitude(122.1234123); // like this
if (location.distanceTo(new Location("")) < 30) { // meters
Toast.makeText(MainActivity.this, "Toast you have reached",
Toast.LENGTH_SHORT).show();
}

Related

How Can I animate Bing map pushpins based on a live GPS feed

I have looked over the bing maps documentation trying to find an answer to my question. I would prefer to do everything using the bing maps api and not have to add a third party library if possible.
Question: How can I animate a pushpin to make a smooth transition from one set of gps coordinate(longitude/latitude) to another in order to simulate smooth movement of a Pushpin on Bing maps?
Question: can deleting an entire object out of the map.entities array waste enough resources to cause performance issues? If so how can I change the pushpin latitude and longitude properties without deleting the entire object?
Sample code of trying to change the pushpins properties without deleting the object out of the array. This code does not work… I am unsure why it is not working?
map.entities.get(theIndexOfThePushPin)._location.latitude = newLat;
map.entities.get(theIndexOfThePushPin)._location.longitude = newLon;
I create a pushpin like so - This works fine
map.entities.push(new Microsoft.Maps.Pushpin(new Microsoft.Maps.Location(lat, lon), {
text: text,
visible: true,
textOffset: new Microsoft.Maps.Point(0, 5)
}));
Pseudo code for my recursive angular $http call
function BusMoveGPSRefresh() {
$http.get(resourceURL)
.then(function (data) {
if ('if pushpins have not been created') {
//create pushpins...
}
} else {
//delete pushpins out of the array and then recreate them
//with updated lon/lat. Or just update existing objects lon/lat properties if possible?
}
}
BusMoveGPSRefresh();//after everything is done then go get more info and start again. recursion...
}, function (reason) {// if fail than do
console.log(reason);
console.log("This Is not Working!!! Dang!!");
});
}
Any insight into the problem would be greatly appreciated! Thanks!
I could not find a simple answer for adding animation. I did find a site that gave a step by step tutorial on a more in-depth answer on how to animate pushpins.
Answer: 1 -- tutorial on how to animate bing map pushpins
https://blogs.bing.com/maps/2014/08/07/bring-your-maps-to-life-creating-animations-with-bing-maps-javascript/
Answer: 2 -- this is how to update the pushpin location without deleting the pushpin object out of the entities array.
Instead of deleting the entire pushpin object find the pushpin index and then use the property "setLocation()" and then add a new location.
//check to make sure that the lat and lon have
//changed if it is still the same location do nothing. else update
if (map.entities.get(indexOfPushpin).getLocation().latitude != lat
|| map.entities.get(indexOfPushpin).getLocation().longitude != lon) {
map.entities.get(indexOfPushpin).setLocation(new Microsoft.Maps.Location(lat, lon));
}

Wikitude geolocation not updating poi markers wikitude examples

I'm trying to understand the wikitude examples. When I run the example app on my phone, and try one of the POI examples, it loads the poi's into the camera view. However, they always stay relative to me. As I walk around, I can never walk past one, and it appears to always be say 5m away from me. How does one update the wikitide examples so that it shows an absolute geolocation that you can walk around and explore? This seems really simple, but none of the examples online seem relevant to answering this. I have extensively searched the wikitude example docs.
Here is an excerpt from the bottom of the poiatlocation.js file in the architect view -
should I be looking at the js file in the architect world, or in the java code?
locationChanged: function locationChangedFn(lat, lon, alt, acc) {
// request data if not already present
if (!World.initiallyLoadedData) {
var poiData = {
"id": 1,
"longitude": (lon + (Math.random() / 5 - 0.1)),
"latitude": (lat + (Math.random() / 5 - 0.1)),
"altitude": 100.0
};
World.loadPoisFromJsonData(poiData);
World.initiallyLoadedData = true;
}
},
};
/* forward locationChanges to custom function */
AR.context.onLocationChanged = World.locationChanged;
The provided sample implementation creates dummy poi data in the user's vicinity on first location update.
The POIs may be some km away from the user, you can use "lon + 0.001" and "lat + 0.001" to create a closer ones.
Also note, that GPS and Network positioning are usually not very accurate and the sample application uses a very basic "Location Strategy" on Android and the default Location Strategy on iOS - So don't expect in-house movements to cause POI-location changes.
Once you try it outdoors with POIs nearby you will notice the location change effect.
Kind regards
PS.:
In case you want to use a more accurate Location Strategy, please have a look at
http://developer.android.com/guide/topics/location/strategies.html
and overwrite the setLocation implementation of the ARchitectView.
Note: Every architectView.setLocation() in the native environment will also cause a "AR.context.onLocationChanged"-JS-function call.

How to get max zoom for maptype in location

On Google Maps' JS API reference page, it says that the method getMaxZoomAtLatLng:
Returns the maximum zoom level available at a particular LatLng for
the Satellite map type.
For some reason, the terrain maptype bottoms out at level 15 in Calgary (for example) but the Satellite maptype can go all the way to zoom 19. I have two map services running simulataneously, and I want the maps to be in sync, but they can't sync up if they can't reach the same zoom level.
So, basically I want to know when the terrain map (or any maptype) can't cope, and trigger some special case functions.
Is there a method, or an alternative, for getting the maximum zoom for a location for a specific map type (since the above mentioned method only works for Satellite)?
Well, one solution I've decided to go with in the meantime is to attach a zoom-end handler to my ArcGIS map (could easily do this with Leaflet as well) and a maptypeid_changed handler to the Google map.
So, for the ArcGIS map (eMap) I did this:
eMap.on('zoom-end', function (e) {
// map zooms are synced
gMap.setCenter(esri.geometry.webMercatorToGeographic(e.extent.getCenter()));
gMap.setZoom(e.level);
// if the google map couldn't do it, reset eMap
if (gMap.getZoom() !== e.level) {
eMap.setZoom(gMap.getZoom());
// runs the handler again
}
});
And if the google map was set to Satellite, then changed, it also needed to trigger the same check, so I forced it to execute another zoomEnd handler:
google.maps.event.addListener(gMap, 'maptypeid_changed', function () {
// for some reason, ESRI has issues setting zoom to current zoom
// so it has to run an initial check before calling zoomEnd
if (gMap.getZoom() !== eMap.getZoom()) {
eMap.setZoom(gMap.getZoom());
}
});
Hope this helps someone, but really, I'm looking forward to seeing a better solution than this. Seems like an awfully complicated approach to merely firing a function if Google's maptype can't reach a certain zoom level.

google Maps: $.goMap() with custom overlayMapType

First: I try to remake a Website called regionalkarten.com
It's a German publisher of Maps. This page uses the Google API v2 to show our custom maps.
My Job is to update the Page to API v3.
Now I found the jQuery GoMap Plugin and I try to use it, but it doesn't seem to support custom maps.
I tried to define a Overly with the custom Map
var ehsTypeBOptions =
{
getTileUrl: function(coord, zoom)
{
var x = coord.x;
var y = coord.y;
return "http://regionalkarten.com/_map/ehs_village_maps/is_maps/z"+zoom+"/"+coord.y+"/"+coord.x+".png";
},
tileSize: new google.maps.Size(256, 256),
};
and load it into the map with:
map.overlayMapTypes.insertAt(0, new google.maps.ImageMapType(ehsTypeBOptions));
That works fine without GoMap. So I tried:
$.goMap.overlayMapTypes.insertAt(0, new google.maps.ImageMapType(ehsTypeBOptions));
and guess what, it didn't work :(
GoMaps Webpage and Google aren't very helpful. Keep in mind that I have to load the custom map into an overlay. I need the real google maps behind the overlay because our maps are not gapless.
I hope you got some ideas or experience with GoMap.
Thank you.
$.goMap does not return the native google.maps.Map-instance, so you can't use the Maps-API-methods there.
The google.maps.Map-instance may be accessed via $.goMap.map .
Beyond that: I would suggest not to use this library, there haven't been any updates since 1 year, and this all can be done without any additional library.
More important: before you continue working with ImageMapType, this is not the right MapType for you, because it appears that the TileServer don't serve tiles for the complete world.
When the user pans or zooms so that a area is in viewport where no tile is available, this area would be shown as a gray space. You better use a Overlay MapType and set the background-image of the overlays to the TileUrl(additionally you may use a condition that checks if a Tile is available at all to reduce unnecessary request to the tile-server)

Bing Maps API v7 limit by bounds

So I'm trying to use the Search Module of the Bing Maps AJAX API (v7), and I've noticed that in the Interactive SDK for it you can pass in a property called bounds which you give a bounding box to search within. The example simply uses the map's current bounding box so theoretically, if you zoom in, a new search should simply show you results within your zoomed in area, right?
Well here's the issue: Add the following code at the end of the example code in the Interactive SDK:
Microsoft.Maps.Events.addHandler(map, 'viewchange', searchRequest);
What this should do is every time you move around the map or zoom in or out, it should fire a new search with the new bounding area of the map... I say this because of the line that looks like this: bounds: map.getBounds(),. What actually happens is that it bounces back to where it was initially before zooming.
Call me crazy, but is the bounds property just being completely ignored? Does anyone know how to limit the search results to the currently visible map area?
Lastly: Is it just me, or are the API docs for V7 rather incomplete? I've managed to find a few things by inspecting stuff in the Chrome console that doesn't appear in the API docs.
Update: This is what my call to the search function looks like:
searchManager.search({
bounds: map.getBounds(),
callback: searchSuccess,
count: 20,
entityType:"Business",
errorCallback: searchFail,
startIndex: 0,
userData: userData,
what: what,
where: search
});
I have not personally used on view changed as I'm not sure that was available when I migrated from 6.0.
I'll share an alternative route I went that gets the trick done.
My search functionality also puts a Microsoft.Maps.Pushpin exactly where the user searched ("You are here!").
I then I create a boundary from the pushpin:
var viewBoundaries = Microsoft.Maps.LocationRect.fromLocations(pushpin.getLocation());
Then set the Map.setView properties for bounds. (Aswell as zoom in my case)
map.setView({ bounds: viewBoundaries });
map.setView({ zoom: 10 });
If you are not using a pushpin, you can simply create the view boundary from the location class.
MSDN Location Class

Categories