Using Google Places API? - android

First of all I want to say that I have checked all the related answers to this question and none of them is working for me as I think they are now old and doesn't seem to work with the new apis.
How to use Google Places API in Android?
Can i use google Places API in android?
Google Places API - android
Above are the few links that I have checked.
I am trying to get the nearby restaurants using the places api in which radius will be defined by user using a seekbar.
Here is how I am creating my request
private String getUrl(double latitude, double longitude, String nearbyPlace, int radius) {
StringBuilder googlePlacesUrl = new StringBuilder("https://maps.googleapis.com/maps/api/place/search/json?");
googlePlacesUrl.append("location=" + latitude + "," + longitude);
googlePlacesUrl.append("&radius=" + radius);
googlePlacesUrl.append("&type=" + "restaurants");
googlePlacesUrl.append("&sensor=true");
googlePlacesUrl.append("&keyword=" + nearbyPlace);
googlePlacesUrl.append("&key=" + "xxxxxxxxxxxxxx");
Log.d("getUrl", googlePlacesUrl.toString());
return (googlePlacesUrl.toString());
}
I pass the above created url to an asynctask to fetch the result from it.
But everytime I am trying to request I get the below error.
{ "error_message" : "This IP, site or mobile application is not authorized to use this API key. Request received from IP address 103.226.226.47, with empty referer", "html_attributions" : [], "results" : [], "status" : "REQUEST_DENIED"}
I have signed up for google cloud platform too in case that is the issue but that doesn't help either.

I solved the problem myself.Everything I did was correct. Problem was that google places api says it takes 5 minutes after enabling to get activated. But in real it took more time than that. So I was actually checking after almost exact 5 minutes and it was not working. I left it for about 2-3 hours and it started working after that.

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.

How to use a google distant matrix api key and an google maps api key in one app?

im programming an app for android that helps me to find the optimal parking space in my hometown.
For that I'm using Google maps API in for android. I managed to get it to work to display the car parks in the city.
Now I want to use google distant matrix API to calculate the traveltime by car between my position and the different car parks and additionally the traveltime by foot from the car parks to a user specific location in the town.
Since I have to use
String url = "https://maps.googleapis.com/maps/api/distancematrix/json?"
+ "origins=" + start.latitude + "," + start.longitude
+ "&destinations=" +waypoints+"&sensor=false&mode=driving&key=GOOGLE_key";
I need to add an API key for GOOGLE_key.
I already have an API key for the distant matrix but I'm hesitating to use that in the code, since on the tutorials they advise against that.
Now to my questions:
How and where can I store that key?
I want to use something like ... + "&sensor=false&mode=driving&key=" + GOOGLE_key; without using the API key in the code.
Additional Info:
In my AndroidManifest.xml is:
android:name="com.google.android.geo.API_KEY"
android:value="#string/google_maps_key"
and in google_maps_api.xml:
<string name="google_maps_key" templateMergeStrategy="preserve" translatable="false">xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx</string>
Thank you for all your help.
Create a variable like GOOGLE_key, then attach google_maps_key string to this via getResources().getSring(). Now, you can use "&sensor=false&mode=driving&key=" + GOOGLE_key;

How to access the OSM API

I am making an app where I need access to the maxspeed in the OSM database. I found the api http://overpass-api.de/api/ in the OSM wiki http://wiki.openstreetmap.org/wiki/Overpass_API but I can't find a way to access it and when I search the api online it reaturns the Forbidden error.
How can I program my app to access the api so I can query the database json to find the maxspeed for my android app.
OSMBonusPack (an addon lib to osmdroid) has an OverpassAPIProvider, ready to use, without your "Forbidden" issue.
If it doesn't exactly fit your need, looking at the source code should help you to implement what you want.
EDIT
Using OverpassAPI may not be straightforward to get the "current" maxspeed ...
Following mmd suggestion, here is the piece of code from velociraptor to build their OverpassAPI request string:
private String getOsmQuery(Location location) {
return "[out:json];" +
"way(around:15,"
+ location.getLatitude() + ","
+ location.getLongitude() +
")" +
"[\"highway\"];out body geom;";
}
This may help...

Using Google Maps and Baidu Maps in same app

I'm wondering if there are anyone out that have implemented Google Maps V2 and Baidu Maps in the same version; because GM doesn't work as intended in China?
Or should I split the project into two branches instead? However it would be nice to skip having two branches to maintain.
My solution for this was to implement GM as usual, however if the user has China set (via settings) static maps is to be used, BUT the static map is fetched from Baidu instead of google.
staticUrl = "http://api.map.baidu.com/staticimage?center="
+ location.getLongitude() + "," + location.getLatitude()
+ "&width=" + width + "&height=" + width + "&zoom=15"
+ "&markers=" + location.getLongitude() + "," + location.getLatitude();
Result of https://api.map.baidu.com/staticimage?center=121,31&width=300&height=300&zoom=15:
This method is NOT recommended if trying to implement a real map solution.
Since I have different locations only used by different countries, this solution could be used.
So, that is how I solved it. Hope someone finds this helpful.
Also, I have found that if you use http://ditu.google.cn while in China, it does work.
When using on-line maps in China for your application, whether it's Google Maps or Baidu, there is a transformation of latitude and longitude for legal reasons.
The satellite view in Google Maps uses "Earth" (WGS-84) coordinates. The map view of GMaps in China uses "Mars" coordinates (GCJ-02), and there is code to convert between the two. Baidu maps use the "Bearpaw" coordinates, with a different offset. The Baidu Map API has a demo converting between Google's coordinates and its own systems.
In China, GPS, like everything, has an extra layer of complication :)
If you have built this app, please post the details. Having an English interface to Baidu maps would be great.
You can use both Google Maps and Baidu Maps side by side, but make sure to convert from the WGS-84 coordinates (used by most of the world) to Baidu's coordinates (BD-09, different from China's GCJ-02). Here's some code that does that, based on an example from the Baidu Maps API:
// Google coordinates
var gPoint = new BMap.Point(121.4914, 31.2423); // lon, lat of the Bund Museum in Shanghai - https://www.google.com/maps/#31.2423,121.4914,19z
// gPoint = new BMap.Point(-122.0851053, 37.4219593); // lon, lat of the Googleplex (no Baidu map data but zooms out in Mountain View)
var labelOffset = { offset: new BMap.Size(20, -10) };
// Initialize map
var map = new BMap.Map('allmap');
map.centerAndZoom(gPoint, 15);
map.addControl(new BMap.ScaleControl({anchor: BMAP_ANCHOR_TOP_LEFT})); // add scale
map.addControl(new BMap.NavigationControl());
map.addControl(new BMap.MapTypeControl()); // map type control: street/satellite/2.5D
map.enableScrollWheelZoom(); // mouse wheel scroll is disabled by default
// Add Google marker and label
var markerG = new BMap.Marker(gPoint);
map.addOverlay(markerG);
markerG.setLabel(new BMap.Label('Google coordinates marker appears<br/>at incorrect location on Baidu Map', labelOffset));
// Coordinate conversion ... GCJ-02 coordinates ... Baidu coordinates
BMap.Convertor.translate(gPoint, 2, function (point) {
var marker = new BMap.Marker(point);
map.addOverlay(marker);
marker.setLabel(new BMap.Label('Converted to Baidu coordinates:<br/>' +
point.lng + ', ' +
point.lat +
'<br/>(note the offset of ' + (map.getDistance(gPoint, point)).toFixed(2) + ' meters)',
labelOffset));
map.addOverlay(new BMap.Polyline([gPoint, point])); // draw a line between points
});
<style type="text/css">
body, html,#allmap {width: 100%;height: 100%;overflow: hidden;margin:0;font-family:"微软雅黑";}
</style>
<script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=gd0GyxGUxSCoAbmdyQBhyhrZ"></script>
<script type="text/javascript" src="http://developer.baidu.com/map/jsdemo/demo/convertor.js"></script>
<div id="allmap"></div>
If the snippet above doesn't work due to the way StackOverflow sandboxes scripts, try the JSbin demo of Google -> Baidu coordinates conversion instead.
If you must perform the conversion offline, check out the evil transform project on GitHub.
It's unclear though what coordinate types browsers localized in Chinese will return via the navigator.geolocation API. I've made a test app for that and posted the question at
Showing navigator.geolocation.getCurrentPosition in Baidu Maps.
Further reading:
What causes the GPS shift in China?
Restrictions on geographic data in China
PROBABLY a bit late to the party, but I accidentally stumbled across something recently which might help you.
I tried baidu maps and it was shockingly difficult to setup and terrible to use so I had a look around and suddenly, google maps worked for me without a vpn!
I realised that the old google china server was still active and if you try:
maps.google.cn
you'll find that creating an iframe using the google.cn address works!
Try to use this way with Google coordinate
http://api.map.baidu.com/marker?location=39.916979519873,116.41004950566&output=html
If your server can access GM without issues (eg. your hosting is not in China mainland or it is but has uncensored connection), why don't you have server do loading data from GM and route it to user instead? We did that for few projects in the past, worked like a charm.
p.s. you could make php pull static map from GM for requested long/lat, store it into temp file on server, then pass back url to the temp file. From user's perspective they would be looking at (static) GM.
p.p.s. If you need user to be able to use GM's UI (do pan/zoom) then you'd need a bit more complex php that would alter all JS loaded from GM so all data would still be requested to your server which would then get maps - so basically to avoid any requests from client machine to be sent to GM server, but all to be sent to yours instead.

Showing a marker at a geo:-url in Android Maps

Is it possible not only to have Google Maps on Android show a given coordinate in the Maps Application but have also a marker (or pin) set at the location?
I read the documentation at https://developer.android.com/guide/appendix/g-app-intents.html but it only lets me set the zoom level.
Right now I use the following code to show a place in Google Maps on Android:
Double lat = 53.3;
Double lng = 13.4;
final String uriString = "geo:" + lat + ',' + lng + "?z=15";
Intent showOnMapIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(uriString));
startActivity(showOnMapIntent);
Is it possible to have a marker there or do I need to use a MapActivity?
Where can I find the complete documentation on the url parameters that the Maps application understands?
Can I use a different url prefix? For example "https://maps.google.de/maps?"?
Maps has an intent-filter matching this scheme/host/pathPrefix.
Where can I find documentation on which parameters Google Maps for Android actually supports with this url?
Dirk, have you tried geo:0,0?q=lat,lng?
it is displaying a marker on my nexus 5.
It works with the follwoing url:
final String uriString = "http://maps.google.com/maps?q=" + lat + ',' + lng + "("+ label +")&z=15";
The reverse geo coded address is shown.
I found documentation to the supported parameters here. This is not the documentation for Androids Google Maps but what I tried works.
Note: it should be noted that the original question was in regards to the the geo: URI to launch the Google Maps app (see Android Developer Reference Intents List, whereas this answer might launch a web view with the Google Maps website depending on what App the user chooses for this Intent.
try this:
http://maps.google.com/?saddr=34.052222,-118.243611
and to get the complete route between two points:
http://maps.google.com/?saddr=34.052222,-118.243611&daddr=37.322778,-122.031944

Categories

Resources