'Google maps' Navigation application - android

How to open google maps apk via another apk on android or ios in flutter react-native .. or any mobile technology. I would like to make a navigation system in my application so I want to directly use google maps through my application. Can someone help me please?

To open Google Maps app from your app you could do something like this.
First set up your url String (what you will send to Google maps app so it knows what directions give):
String url = 'https://www.google.com/maps/dir/?api=1&origin=' +
currentLocation.latitude.toString() +
',' +
currentLocation.longitude.toString() +
' &destination=' +
lat.toString() +
',' +
lon.toString() +
'&travelmode=driving&dir_action=navigate';
_launchURL(url);
Where currentLocation means the user current location, and lat and lon means the destination.
Then just launch that url, using an urlLauncher:
void _launchURL(String url) async {
if (await canLaunch(url)) {
await launch(url);
} else {
throw 'Could not launch $url';
}
}

Related

Protect Google Maps API key with Restriction for Ionic app

I am working on ionic app and I want to redirect user from app to google map application for showing directions to user but when I am setting a Key restriction to NONE it works perfectly.
But when I set restriction to Android apps and provide a proper Package name & SHA-1 It give me error: Google Maps JavaScript API error: RefererNotAllowedMapError.
I think it is because:
ionic app is basically a webview. (which I am using)
and if this is the reason how can I protect my API key?
I use code to open Google map in android app is
showDirection(currentLocation, destLocation) {
let destination = destLocation.latitude + ',' + destLocation.longitude;
var directionsService = new google.maps.DirectionsService;
directionsService.route({
origin: currentLocation,
destination: destination,
travelMode: 'DRIVING'
}, function (response, status) {
if (status === 'OK') {
let mapUrl = 'http://maps.google.com/?';
var route = response.routes[0];
route.legs.forEach((value, index) => {
if (index == 0) {
mapUrl += 'saddr' + value.start_address + '&daddr=' + value.end_address;
} else {
mapUrl += '+to:' + value.end_address;
}
});
window.location.href = mapUrl;
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
can someone help?
Android app restriction is only valid for Google Maps SDK for Android. In your case when you use Ionic with WebView and Google Maps JavaScript API the only supported restriction is HTTP referrer.
You can check yourself which type of restriction is supported by each API on this page
https://developers.google.com/maps/faq#keysystem
In order to set valid HTTP referrer restriction in your Ionic app you should check what value has window.location.href when you open a map in your WebView.
For example, if the window.location.href is something like file://some/path you should use this value as referrer.
Also note that URLs with a file:// protocol require special representation as explained in
https://developers.google.com/maps/documentation/javascript/get-api-key#restrict_key
Note: file:// referers need a special representation to be added to the key restriction. The "file://" part should be replaced with "_file_url_" before being added to the key restriction. For example, "file:///path/to/" should be formatted as "_file_url_//path/to/*". After enabling file:// referers, it is recommended you regularly check your usage, to make sure it matches your expectations.
UPDATE
I believe you can avoid using DirectionsService and open Google Maps directly with Google Maps URLs in directions mode
The code snippet might be
showDirection(currentLocation, destLocation) {
const destination = destLocation.latitude + ',' + destLocation.longitude;
let mapUrl = "https://www.google.com/maps/dir/?api=1";
mapUrl += "&origin=" + currentLocation;
mapUrl += "&destination=" + destination;
mapUrl += "&travelmode=driving";
mapUrl += "&dir_action=navigate";
window.location.href = mapUrl;
}
In this scenario you don't need using Google Maps JavaScript API, you don't need an API key and you don't pay for using Maps JavaScript API service.

xamarin form disallowed_useragent with webview when using Google api

I am working on Xamarin cross platform app where I am implementing Google Sign on.
From browser and postman, I am able to authticate and get user data using api.
But when I am using in Xamarin forms webview, I am getting error of disallowed_useragent .
Because Google no longer supports webview request. So I need to set user agent in andriod as well as iOS app OR something to setup in PCL project that will be used by both platform.
I didn't find solution to solve this problem
Here is my code :
private async void LoginWithGoogle_Clicked(object sender, EventArgs e)
{
ShowLoader(true);
var authRequest =
"https://accounts.google.com/o/oauth2/v2/auth"
+ "?response_type=code"
+ "&scope=email%20profile"
+ "&redirect_uri=" + Constants.GoogleRedirectUri
+ "&client_id=" + Constants.GoogleClientId;
var webView = new WebView
{
Source = authRequest,
HeightRequest = 1
};
webView.Navigated += WebViewOnNavigatedForGoogle;
Content = webView;
ShowLoader(false);
}
Check out https://github.com/xamarin/Xamarin.Auth, there is working solution :)

Phonegap google maps api query not working

I am developing a simple android app using phonegap that sends a google maps geocoding api request with lat,lan location and returns an address.
When working using my desktop, everything works fine!
Once I build the app using the adobe phonegap cloud builder, it does not work. in addition, I am unable to debug as nothing is presented on the app. it simply shows an empty value.
Could this be a CORS issue? HTTPS? Some issue using a mobile user-agent for google maps requests? I am unsure. appreciate any help!
this is my code:
function maps_api(latlng){
var divdata = $('div#data');
divdata.text('cleared');
updateStatus('Starting google api: ');
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
updateStatus(this.responseText);
var myArr = JSON.parse(this.responseText);
var divdata = $('div#data');
divdata.text(myArr["results"][0]["formatted_address"]);
}
else
{
updateStatus(this.responseText);
var divdata = $('div#data');
divdata.text(xhttp.statusText);
}
};
xhttp.open("GET", "https://maps.googleapis.com/maps/api/geocode/json?latlng=" + latlng + "&key=myprivatekey", true);
xhttp.send();
}
I managed to resolve this by installing the whitelist-plugin and allowing communication to google maps server

Create a link that opens the appropriate map app on any device, with directions to destination

I rather thought this would not be so hard to find out but appearantly it is not easy to find an awesome cross device article, like you'd expect.
I want to create a link which opens either the mobile device's browser and surf to google maps OR open a maps app (Apple Maps or Google Maps) and directly starting a route, i.e.: start at the current location, end at a given point (lat/long).
I can test on two devices (beside browserstack), an Android and an iPhone.
The following link works only on the Android:
Take me there!
Clicking this link in iPhone's Chrome, this weirdly opens Google Maps in desktop version with ads on the mobile app...
This one only works on iOS, opening Apple Maps asking me to enter a start location (i can pick "Current Location") and start the route = desired behavior. Clicking this link completely fails on Android:
Take me there!
Notice the maps:// protocol.
Is there an elegant cross device way of creating such a link? One link that works on all main mobiles?
Thanks
UPDATE: Solution found (kinda)
Here is what I've come up with. It's not quite what I imagined, though it's working.
var ua = navigator.userAgent.toLowerCase(),
plat = navigator.platform,
protocol = '',
a,
href;
$.browser.device = ua.match(/android|webos|iphone|ipad|ipod|blackberry|iemobile|opera/i) ? ua.match(/android|webos|iphone|ipad|ipod|blackberry|iemobile|opera/i)[0] : false;
if ($.browser.device) {
switch($.browser.device) {
case 'iphone':
case 'ipad':
case 'ipod':
function iOSversion() {
if (/iP(hone|od|ad)/.test(navigator.platform)) {
// supports iOS 2.0 and later: <http://bit. ly/TJjs1V>
var v = (navigator.appVersion).match(/OS (\d+)_(\d+)_?(\d+)?/);
return [parseInt(v[1], 10), parseInt(v[2], 10), parseInt(v[3] || 0, 10)];
}
}
var ver = iOSversion() || [0];
if (ver[0] >= 6) {
protocol = 'maps://';
}
else {
protocol = 'http://maps.google.com/maps';
}
break;
case 'android':
default:
protocol = 'http://maps.google.com/maps';
break;
}
a.attr('href', protocol + href)
the maps:// protocol is the url scheme for the apple maps app, which will only start working on ios 6 or higher. There are ways to test if gmaps is installed and then chose what to do with the url, but that was kind of too much for what I intended. So i just ended up creating a maps:// OR maps.google.com/ link, using the above parameters.
** UPDATE **
sadly, $.browser.device don't work since jquery 1.9
(source - http://api.jquery.com/jquery.browser )
I haven't worked much with phones, so I dont't know if this would work. But just from a html/javascript point of view, you could just open a different url depending on what the user's device is?
<a style="cursor: pointer;" onclick="myNavFunc()">Take me there!</a>
function myNavFunc(){
// If it's an iPhone..
if( (navigator.platform.indexOf("iPhone") != -1)
|| (navigator.platform.indexOf("iPod") != -1)
|| (navigator.platform.indexOf("iPad") != -1))
window.open("maps://www.google.com/maps/dir/?api=1&travelmode=driving&layer=traffic&destination=[YOUR_LAT],[YOUR_LNG]");
else
window.open("https://www.google.com/maps/dir/?api=1&travelmode=driving&layer=traffic&destination=[YOUR_LAT],[YOUR_LNG]");
}
Interestingly, http://maps.apple.com links will open directly in Apple Maps on an iOS device, or redirect to Google Maps otherwise (which is then intercepted on an Android device), so you can craft a careful URL that will do the right thing in both cases using an "Apple Maps" URL like:
http://maps.apple.com/?daddr=1600+Amphitheatre+Pkwy,+Mountain+View+CA
Alternatively, you can use a Google Maps url directly (without the /maps URL component) to open directly in Google Maps on an Android device, or open in Google Maps' Mobile Web on an iOS device:
http://maps.google.com/?daddr=1+Infinite+Loop,+Cupertino+CA
just bumped in this question and found here all the answers
I took some of the codes above and made simple js function that works on
android and iphone (it supports almost every android and iphones).
function navigate(lat, lng) {
// If it's an iPhone..
if ((navigator.platform.indexOf("iPhone") !== -1) || (navigator.platform.indexOf("iPod") !== -1)) {
function iOSversion() {
if (/iP(hone|od|ad)/.test(navigator.platform)) {
// supports iOS 2.0 and later
var v = (navigator.appVersion).match(/OS (\d+)_(\d+)_?(\d+)?/);
return [parseInt(v[1], 10), parseInt(v[2], 10), parseInt(v[3] || 0, 10)];
}
}
var ver = iOSversion() || [0];
var protocol = 'http://';
if (ver[0] >= 6) {
protocol = 'maps://';
}
window.location = protocol + 'maps.apple.com/maps?daddr=' + lat + ',' + lng + '&ll=';
}
else {
window.open('http://maps.google.com?daddr=' + lat + ',' + lng + '&ll=');
}
}
The html:
<a onclick="navigate(31.046051,34.85161199999993)" >Israel</a>
This works for me on all devices [ iOS, Android and Window Mobile 8.1 ].
Does not look like the best way by any means... but cannot be more simpler :)
<a href="bingmaps:?cp=18.551464~73.951399">
<a href="http://maps.apple.com/maps?q=18.551464, 73.951399">
Open Maps
</a>
</a>
http://jsbin.com/dibeq
if (navigator.geolocation) { //Checks if browser supports geolocation
navigator.geolocation.getCurrentPosition(function (position) {
var latitude = position.coords.latitude; //users current
var longitude = position.coords.longitude; //location
var coords = new google.maps.LatLng(latitude, longitude); //Creates variable for map coordinates
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer();
var mapOptions = //Sets map options
{
zoom: 15, //Sets zoom level (0-21)
center: coords, //zoom in on users location
mapTypeControl: true, //allows you to select map type eg. map or satellite
navigationControlOptions:
{
style: google.maps.NavigationControlStyle.SMALL //sets map controls size eg. zoom
},
mapTypeId: google.maps.MapTypeId.ROADMAP //sets type of map Options:ROADMAP, SATELLITE, HYBRID, TERRIAN
};
map = new google.maps.Map( /*creates Map variable*/ document.getElementById("map"), mapOptions /*Creates a new map using the passed optional parameters in the mapOptions parameter.*/);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('panel'));
var request = {
origin: coords,
destination: 'BT42 1FL',
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
});
}
Well no, from an iOS developer prospective, there are two links that I know of that will open the Maps app on the iPhone
On iOS 5 and lower: http://maps.apple.com?q=xxxx
On iOS 6 and up: http://maps.google.com?q=xxxx
And that's only on Safari. Chrome will direct you to Google Maps webpage.
Other than that you'll need to use a URL scheme that basically beats the purpose because no android will know that protocol.
You might want to know, Why Safari opens the Maps app and Chrome directs me to a webpage?
Well, because safari is the build in browser made by apple and can detect the URL above. Chrome is "just another app" and must comply to the iOS Ecosystem. Therefor the only way for it to communicate with other apps is by using URL schemes.
Simple URL :
https://www.google.com/maps/dir/?api=1&destination=[LAT],[LNG]
This url is specific for routing.
Reference
I found that this works across the board:
<a href="https://www.google.com/maps/place/1+Fake+Street,+City+Province/State>Get Directions</a>
For desktops/laptops the user has to click Directions when that map loads, but from my testing all mobile devices will load that link in the Google Maps app without difficulty.
Based on the documentation the origin parameter is optional and it defaults to the user's location.
... Defaults to most relevant starting location, such as user location, if available. If none, the resulting map may provide a blank form to allow a user to enter the origin....
ex: https://www.google.com/maps/dir/?api=1&destination=Pike+Place+Market+Seattle+WA&travelmode=bicycling
For me this works on Desktop, IOS and Android.
The URL syntax is the same regardless of the platform in use
String url = "https://www.google.com/maps/search/?api=1&query=" + latitude + ","+
longitude;
In Android or iOS the URL launches Google Maps in the Maps app, If the Google Maps app is not installed, the URL launches Google Maps in a browser and performs the requested action.
On any other device, the URL launches Google Maps in a browser and performs the requested action.
here's the link for official documentation
https://developers.google.com/maps/documentation/urls/guide

Common link for current location in google maps for ios and android using html

I can't seem to find a common answer anywhere. It seems like there isn't a way to support both Android and iPhone for links opening in their native maps application with their current location set.
From what I've been able to find, the iPhone does it like this:
saddr=Current%20Location
and android you can just leave "saddr" blank. I'm not even thinking of BlackBerries yet. I suppose there is probably a way to do this with JavaScript, but it don't think it should be that complicated.
For now what I'm doing is using html5 geolocation to grab the latitude and longitude instead relying on the OS to interpret the current location.
HTML:
<a id="directions" class="callout" href="http://maps.google.com/maps?daddr=address">
JavaScript:
$('#directions').bind('click', function (e) {
var href = $(this).attr('href');
if (navigator.geolocation) {
e.preventDefault();
navigator.geolocation.getCurrentPosition(function (position) {
geoLink(position.coords.latitude, position.coords.longitude, href);
});
}
function geoLink(lat, log, href) {
var location = href + '&saddr=' + lat + ',' + log;
window.location.href = location;
}

Categories

Resources