vtm-app: revive / update with latest VTM, closes #90

This commit is contained in:
Emux
2016-07-21 20:22:22 +03:00
parent c67b35a277
commit 436b66be82
133 changed files with 10436 additions and 0 deletions

View File

@@ -0,0 +1,163 @@
package org.osmdroid.location;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.oscim.core.BoundingBox;
import org.oscim.core.GeoPoint;
import org.osmdroid.utils.BonusPackHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.HashMap;
/**
* POI Provider using Flickr service to get geolocalized photos.
*
* @author M.Kergall
* @see "http://www.flickr.com/services/api/flickr.photos.search.html"
*/
public class FlickrPOIProvider implements POIProvider {
final static Logger log = LoggerFactory.getLogger(FlickrPOIProvider.class);
protected String mApiKey;
private final static String PHOTO_URL = "http://www.flickr.com/photos/%s/%s/sizes/o/in/photostream/";
/**
* @param apiKey the registered API key to give to Flickr service.
* @see "http://www.flickr.com/help/api/"
*/
public FlickrPOIProvider(String apiKey) {
mApiKey = apiKey;
}
private String getUrlInside(BoundingBox boundingBox, int maxResults) {
StringBuffer url = new StringBuffer(
"http://api.flickr.com/services/rest/?method=flickr.photos.search");
url.append("&api_key=" + mApiKey);
url.append("&bbox=" + boundingBox.getMinLongitude());
url.append("," + boundingBox.getMinLatitude());
url.append("," + boundingBox.getMaxLongitude());
url.append("," + boundingBox.getMaxLatitude());
url.append("&has_geo=1");
// url.append("&geo_context=2");
// url.append("&is_commons=true");
url.append("&format=json&nojsoncallback=1");
url.append("&per_page=" + maxResults);
// From Flickr doc:
// "Geo queries require some sort of limiting agent in order to prevent the database from crying."
// And min_date_upload is considered as a limiting agent. So:
url.append("&min_upload_date=2005/01/01");
// Ask to provide some additional attributes we will need:
url.append("&extras=geo,url_sq");
url.append("&sort=interestingness-desc");
return url.toString();
}
/* public POI getPhoto(String photoId){ String url =
* "http://api.flickr.com/services/rest/?method=flickr.photos.getInfo"
* +
* "&api_key=" + mApiKey + "&photo_id=" + photo Id +
* "&format=json&nojsoncallback=1"; log.debug( * "getPhoto:"+url); String
* jString =
* BonusPackHelper.requestStringFromUrl(url); if (jString == null)
* {
* log.error( * "FlickrPOIProvider: request failed.");
* return null; } try { POI poi = new POI(POI.POI_SERVICE_FLICKR);
* JSONObject jRoot = new JSONObject(jString); JSONObject jPhoto =
* jRoot.getJSONObject("photo"); JSONObject jLocation =
* jPhoto.getJSONObject("location"); poi.mLocation = new GeoPoint(
* jLocation.getDouble("latitude"),
* jLocation.getDouble("longitude"));
* poi.mId = Long.parseLong(photoId); JSONObject jTitle =
* jPhoto.getJSONObject("title"); poi.mType =
* jTitle.getString("_content");
* JSONObject jDescription = jPhoto.getJSONObject("description");
* poi.mDescription = jDescription.getString("_content");
* //truncate
* description if too long: if (poi.mDescription.length() > 300){
* poi.mDescription = poi.mDescription.substring(0, 300) +
* " (...)"; }
* String farm = jPhoto.getString("farm"); String server =
* jPhoto.getString("server"); String secret =
* jPhoto.getString("secret");
* JSONObject jOwner = jPhoto.getJSONObject("owner"); String nsid
* =
* jOwner.getString("nsid"); poi.mThumbnailPath =
* "http://farm"+farm+".staticflickr.com/"
* +server+"/"+photoId+"_"+secret+"_s.jpg"; poi.mUrl =
* "http://www.flickr.com/photos/"+nsid+"/"+photoId; return poi;
* }catch
* (JSONException e) { e.printStackTrace(); return null; } } */
/**
* @param fullUrl ...
* @return the list of POI
*/
public ArrayList<POI> getThem(String fullUrl) {
// for local debug: fullUrl = "http://10.0.2.2/flickr_mockup.json";
log.debug("FlickrPOIProvider:get:" + fullUrl);
String jString = BonusPackHelper.requestStringFromUrl(fullUrl);
if (jString == null) {
log.error("FlickrPOIProvider: request failed.");
return null;
}
try {
JSONObject jRoot = new JSONObject(jString);
JSONObject jPhotos = jRoot.getJSONObject("photos");
JSONArray jPhotoArray = jPhotos.getJSONArray("photo");
int n = jPhotoArray.length();
ArrayList<POI> pois = new ArrayList<POI>(n);
for (int i = 0; i < n; i++) {
JSONObject jPhoto = jPhotoArray.getJSONObject(i);
String photoId = jPhoto.getString("id");
if (mPrevious != null && mPrevious.containsKey(photoId))
continue;
POI poi = new POI(POI.POI_SERVICE_FLICKR);
poi.location = new GeoPoint(
jPhoto.getDouble("latitude"),
jPhoto.getDouble("longitude"));
poi.id = photoId; //Long.parseLong(photoId);
poi.type = jPhoto.getString("title");
poi.thumbnailPath = jPhoto.getString("url_sq");
String owner = jPhoto.getString("owner");
// the default flickr link viewer doesnt work with mobile browsers...
// poi.url = "http://www.flickr.com/photos/" + owner + "/" + photoId + "/sizes/o/in/photostream/";
poi.url = String.format(PHOTO_URL, owner, photoId);
pois.add(poi);
}
// int total = jPhotos.getInt("total");
// log.debug(on a total of:" + total);
return pois;
} catch (JSONException e) {
e.printStackTrace();
return null;
}
}
/**
* @param boundingBox ...
* @param maxResults ...
* @return list of POI, Flickr photos inside the bounding box.
* Null if
* technical issue.
*/
public ArrayList<POI> getPOIInside(BoundingBox boundingBox, String query, int maxResults) {
String url = getUrlInside(boundingBox, maxResults);
return getThem(url);
}
HashMap<String, POI> mPrevious;
public void setPrevious(HashMap<String, POI> previous) {
mPrevious = previous;
}
}

View File

@@ -0,0 +1,186 @@
/*
* Copyright 2012 Hannes Janetzek
*
* This program is free software: you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.osmdroid.location;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.oscim.core.BoundingBox;
import org.oscim.core.GeoPoint;
import org.osmdroid.utils.BonusPackHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
public class FourSquareProvider implements POIProvider {
final static Logger log = LoggerFactory.getLogger(FourSquareProvider.class);
// https://developer.foursquare.com/docs/venues/search
// https://developer.foursquare.com/docs/responses/venue
// https://apigee.com/console/foursquare
protected String mApiKey;
// private static HashMap<String, Bitmap> mIcons =
// (HashMap<String,Bitmap>)Collections.synchronizedMap(new HashMap<String, Bitmap>());
/**
* @param clientSecret the registered API key to give to Flickr service.
* @see "http://www.flickr.com/help/api/"
*/
public FourSquareProvider(String clientId, String clientSecret) {
mApiKey = "client_id=" + clientId + "&client_secret=" + clientSecret;
}
//"https://api.foursquare.com/v2/venues/search?v=20120321&intent=checkin&ll=53.06,8.8&client_id=ZUN4ZMNZUFT3Z5QQZNMQ3ACPL4OJMBFGO15TYX51D5MHCIL3&client_secret=X1RXCVF4VVSG1Y2FUDQJLKQUC1WF4XXKIMK2STXKACLPDGLY
@SuppressWarnings("deprecation")
private String getUrlInside(BoundingBox boundingBox, String query, int maxResults) {
StringBuffer url = new StringBuffer(
"https://api.foursquare.com/v2/venues/search?v=20120321"
+ "&intent=browse"
+ "&client_id=ZUN4ZMNZUFT3Z5QQZNMQ3ACPL4OJMBFGO15TYX51D5MHCIL3"
+ "&client_secret=X1RXCVF4VVSG1Y2FUDQJLKQUC1WF4XXKIMK2STXKACLPDGLY");
url.append("&sw=");
url.append(boundingBox.getMinLatitude());
url.append(',');
url.append(boundingBox.getMinLongitude());
url.append("&ne=");
url.append(boundingBox.getMaxLatitude());
url.append(',');
url.append(boundingBox.getMaxLongitude());
url.append("&limit=");
url.append(maxResults);
if (query != null)
url.append("&query=" + URLEncoder.encode(query));
return url.toString();
}
/**
* @param fullUrl ...
* @return the list of POI
*/
public ArrayList<POI> getThem(String fullUrl) {
// for local debug: fullUrl = "http://10.0.2.2/flickr_mockup.json";
log.debug("FlickrPOIProvider:get:" + fullUrl);
String jString = BonusPackHelper.requestStringFromUrl(fullUrl);
if (jString == null) {
log.error("FlickrPOIProvider: request failed.");
return null;
}
try {
JSONObject jRoot = new JSONObject(jString);
JSONObject jResponse = jRoot.getJSONObject("response");
JSONArray jVenueArray = jResponse.getJSONArray("venues");
int n = jVenueArray.length();
ArrayList<POI> pois = new ArrayList<POI>(n);
for (int i = 0; i < n; i++) {
JSONObject jVenue = jVenueArray.getJSONObject(i);
POI poi = new POI(POI.POI_SERVICE_4SQUARE);
poi.id = jVenue.getString("id");
poi.type = jVenue.getString("name");
// poi.url = jVenue.optString("url", null);
poi.url = "https://foursquare.com/v/" + poi.id;
JSONObject jLocation = jVenue.getJSONObject("location");
poi.location = new GeoPoint(
jLocation.getDouble("lat"),
jLocation.getDouble("lng"));
poi.description = jLocation.optString("address", null);
JSONArray jCategories = jVenue.getJSONArray("categories");
if (jCategories.length() > 0) {
JSONObject jCategory = jCategories.getJSONObject(0);
String icon = jCategory.getJSONObject("icon").getString("prefix");
poi.thumbnailPath = icon + 44 + ".png";
poi.category = jCategory.optString("name");
}
pois.add(poi);
}
return pois;
} catch (JSONException e) {
e.printStackTrace();
return null;
}
}
/**
* @param boundingBox ...
* @param maxResults ...
* @return list of POI, Flickr photos inside the bounding box.
* Null if
* technical issue.
*/
public ArrayList<POI> getPOIInside(BoundingBox boundingBox, String query, int maxResults) {
String url = getUrlInside(boundingBox, query, maxResults);
return getThem(url);
}
public static void browse(final Context context, POI poi) {
// get the right url from redirect, could also parse the result from querying venueid...
new AsyncTask<POI, Void, String>() {
@Override
protected String doInBackground(POI... params) {
POI poi = params[0];
if (poi == null)
return null;
try {
URL url = new URL(poi.url);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setInstanceFollowRedirects(false);
String redirect = conn.getHeaderField("Location");
if (redirect != null) {
log.debug(redirect);
return redirect;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String result) {
if (result == null)
return;
Intent myIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://foursquare.com"
+ result));
context.startActivity(myIntent);
}
}.execute(poi);
}
}

View File

@@ -0,0 +1,215 @@
package org.osmdroid.location;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.oscim.core.BoundingBox;
import org.oscim.core.GeoPoint;
import org.osmdroid.utils.BonusPackHelper;
import org.osmdroid.utils.HttpConnection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Locale;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
/**
* POI Provider using GeoNames services. Currently, "find Nearby Wikipedia" and
* "Wikipedia Articles in Bounding Box" services.
*
* @author M.Kergall
* @see "http://www.geonames.org"
*/
public class GeoNamesPOIProvider {
final static Logger log = LoggerFactory.getLogger(GeoNamesPOIProvider.class);
protected String mUserName;
/**
* @param account the registered "username" to give to GeoNames service.
* @see "http://www.geonames.org/login"
*/
public GeoNamesPOIProvider(String account) {
mUserName = account;
}
private String getUrlCloseTo(GeoPoint p, int maxResults, double maxDistance) {
StringBuffer url = new StringBuffer("http://api.geonames.org/findNearbyWikipediaJSON?");
url.append("lat=" + p.getLatitude());
url.append("&lng=" + p.getLongitude());
url.append("&maxRows=" + maxResults);
url.append("&radius=" + maxDistance); //km
url.append("&lang=" + Locale.getDefault().getLanguage());
url.append("&username=" + mUserName);
return url.toString();
}
private String getUrlInside(BoundingBox boundingBox, int maxResults) {
StringBuffer url = new StringBuffer("http://api.geonames.org/wikipediaBoundingBoxJSON?");
url.append("south=" + boundingBox.getMinLatitude());
url.append("&north=" + boundingBox.getMaxLatitude());
url.append("&west=" + boundingBox.getMinLongitude());
url.append("&east=" + boundingBox.getMaxLongitude());
url.append("&maxRows=" + maxResults);
url.append("&lang=" + Locale.getDefault().getLanguage());
url.append("&username=" + mUserName);
return url.toString();
}
/**
* @param fullUrl ...
* @return the list of POI
*/
public ArrayList<POI> getThem(String fullUrl) {
log.debug("GeoNamesPOIProvider:get:" + fullUrl);
String jString = BonusPackHelper.requestStringFromUrl(fullUrl);
if (jString == null) {
log.error("GeoNamesPOIProvider: request failed.");
return null;
}
try {
JSONObject jRoot = new JSONObject(jString);
JSONArray jPlaceIds = jRoot.getJSONArray("geonames");
int n = jPlaceIds.length();
ArrayList<POI> pois = new ArrayList<POI>(n);
for (int i = 0; i < n; i++) {
JSONObject jPlace = jPlaceIds.getJSONObject(i);
POI poi = new POI(POI.POI_SERVICE_GEONAMES_WIKIPEDIA);
poi.location = new GeoPoint(jPlace.getDouble("lat"),
jPlace.getDouble("lng"));
poi.category = jPlace.optString("feature");
poi.type = jPlace.getString("title");
poi.description = jPlace.optString("summary");
poi.thumbnailPath = jPlace.optString("thumbnailImg", null);
/* This makes loading too long. Thumbnail loading will be done
* only when needed, with POI.getThumbnail() if
* (poi.mThumbnailPath != null){ poi.mThumbnail =
* BonusPackHelper.loadBitmap(poi.mThumbnailPath); } */
poi.url = jPlace.optString("wikipediaUrl", null);
if (poi.url != null)
poi.url = "http://" + poi.url;
poi.rank = jPlace.optInt("rank", 0);
//other attributes: distance?
pois.add(poi);
}
log.debug("done");
return pois;
} catch (JSONException e) {
e.printStackTrace();
return null;
}
}
//XML parsing seems 2 times slower than JSON parsing
public ArrayList<POI> getThemXML(String fullUrl) {
log.debug("GeoNamesPOIProvider:get:" + fullUrl);
HttpConnection connection = new HttpConnection();
connection.doGet(fullUrl);
InputStream stream = connection.getStream();
if (stream == null) {
return null;
}
GeoNamesXMLHandler handler = new GeoNamesXMLHandler();
try {
SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
parser.parse(stream, handler);
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
connection.close();
log.debug("done");
return handler.mPOIs;
}
/**
* @param position ...
* @param maxResults ...
* @param maxDistance ... in km. 20 km max for the free service.
* @return list of POI, Wikipedia entries close to the position. Null if
* technical issue.
*/
public ArrayList<POI> getPOICloseTo(GeoPoint position,
int maxResults, double maxDistance) {
String url = getUrlCloseTo(position, maxResults, maxDistance);
return getThem(url);
}
/**
* @param boundingBox ...
* @param maxResults ...
* @return list of POI, Wikipedia entries inside the bounding box. Null if
* technical issue.
*/
public ArrayList<POI> getPOIInside(BoundingBox boundingBox, int maxResults) {
String url = getUrlInside(boundingBox, maxResults);
return getThem(url);
}
}
class GeoNamesXMLHandler extends DefaultHandler {
private String mString;
double mLat, mLng;
POI mPOI;
ArrayList<POI> mPOIs;
public GeoNamesXMLHandler() {
mPOIs = new ArrayList<POI>();
}
@Override
public void startElement(String uri, String localName, String name,
Attributes attributes) {
if (localName.equals("entry")) {
mPOI = new POI(POI.POI_SERVICE_GEONAMES_WIKIPEDIA);
}
mString = new String();
}
@Override
public void characters(char[] ch, int start, int length) {
String chars = new String(ch, start, length);
mString = mString.concat(chars);
}
@Override
public void endElement(String uri, String localName, String name) {
if (localName.equals("lat")) {
mLat = Double.parseDouble(mString);
} else if (localName.equals("lng")) {
mLng = Double.parseDouble(mString);
} else if (localName.equals("feature")) {
mPOI.category = mString;
} else if (localName.equals("title")) {
mPOI.type = mString;
} else if (localName.equals("summary")) {
mPOI.description = mString;
} else if (localName.equals("thumbnailImg")) {
if (mString != null && !mString.equals(""))
mPOI.thumbnailPath = mString;
} else if (localName.equals("wikipediaUrl")) {
if (mString != null && !mString.equals(""))
mPOI.url = "http://" + mString;
} else if (localName.equals("rank")) {
mPOI.rank = Integer.parseInt(mString);
} else if (localName.equals("entry")) {
mPOI.location = new GeoPoint(mLat, mLng);
mPOIs.add(mPOI);
}
}
}

View File

@@ -0,0 +1,208 @@
package org.osmdroid.location;
import android.content.Context;
import android.location.Address;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.osmdroid.utils.BonusPackHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
/**
* Implements an equivalent to Android Geocoder class, based on OpenStreetMap
* data and Nominatim API. <br>
* See http://wiki.openstreetmap.org/wiki/Nominatim or
* http://open.mapquestapi.com/nominatim/
*
* @author M.Kergall
*/
public class GeocoderNominatim {
final static Logger log = LoggerFactory.getLogger(GeocoderNominatim.class);
public static final String NOMINATIM_SERVICE_URL = "http://nominatim.openstreetmap.org/";
public static final String MAPQUEST_SERVICE_URL = "http://open.mapquestapi.com/nominatim/v1/";
protected Locale mLocale;
protected String mServiceUrl;
/**
* @param context ...
* @param locale ...
*/
protected void init(Context context, Locale locale) {
mLocale = locale;
setService(NOMINATIM_SERVICE_URL); //default service
}
public GeocoderNominatim(Context context, Locale locale) {
init(context, locale);
}
public GeocoderNominatim(Context context) {
init(context, Locale.getDefault());
}
static public boolean isPresent() {
return true;
}
/**
* Specify the url of the Nominatim service provider to use. Can be one of
* the predefined (NOMINATIM_SERVICE_URL or MAPQUEST_SERVICE_URL), or
* another one, your local instance of Nominatim for instance.
*
* @param serviceUrl ...
*/
public void setService(String serviceUrl) {
mServiceUrl = serviceUrl;
}
/**
* Build an Android Address object from the Nominatim address in JSON
* format. Current implementation is mainly targeting french addresses, and
* will be quite basic on other countries.
*
* @param jResult ...
* @return ...
* @throws JSONException ...
*/
protected Address buildAndroidAddress(JSONObject jResult) throws JSONException {
Address gAddress = new Address(mLocale);
gAddress.setLatitude(jResult.getDouble("lat"));
gAddress.setLongitude(jResult.getDouble("lon"));
JSONObject jAddress = jResult.getJSONObject("address");
int addressIndex = 0;
if (jAddress.has("road")) {
gAddress.setAddressLine(addressIndex++, jAddress.getString("road"));
gAddress.setThoroughfare(jAddress.getString("road"));
}
if (jAddress.has("suburb")) {
//gAddress.setAddressLine(addressIndex++, jAddress.getString("suburb"));
//not kept => often introduce "noise" in the address.
gAddress.setSubLocality(jAddress.getString("suburb"));
}
if (jAddress.has("postcode")) {
gAddress.setAddressLine(addressIndex++, jAddress.getString("postcode"));
gAddress.setPostalCode(jAddress.getString("postcode"));
}
if (jAddress.has("city")) {
gAddress.setAddressLine(addressIndex++, jAddress.getString("city"));
gAddress.setLocality(jAddress.getString("city"));
} else if (jAddress.has("town")) {
gAddress.setAddressLine(addressIndex++, jAddress.getString("town"));
gAddress.setLocality(jAddress.getString("town"));
} else if (jAddress.has("village")) {
gAddress.setAddressLine(addressIndex++, jAddress.getString("village"));
gAddress.setLocality(jAddress.getString("village"));
}
if (jAddress.has("county")) { //France: departement
gAddress.setSubAdminArea(jAddress.getString("county"));
}
if (jAddress.has("state")) { //France: region
gAddress.setAdminArea(jAddress.getString("state"));
}
if (jAddress.has("country")) {
gAddress.setAddressLine(addressIndex++, jAddress.getString("country"));
gAddress.setCountryName(jAddress.getString("country"));
}
if (jAddress.has("country_code"))
gAddress.setCountryCode(jAddress.getString("country_code"));
/* Other possible OSM tags in Nominatim results not handled yet: subway,
* golf_course, bus_stop, parking,... house, house_number, building
* city_district (13e Arrondissement) road => or highway, ... sub-city
* (like suburb) => locality, isolated_dwelling, hamlet ...
* state_district */
return gAddress;
}
/**
* @param latitude ...
* @param longitude ...
* @param maxResults ...
* @return ...
* @throws IOException ...
*/
public List<Address> getFromLocation(double latitude, double longitude, int maxResults)
throws IOException {
String url = mServiceUrl
+ "reverse?"
+ "format=json"
+ "&accept-language=" + mLocale.getLanguage()
//+ "&addressdetails=1"
+ "&lat=" + latitude
+ "&lon=" + longitude;
log.debug("GeocoderNominatim::getFromLocation:" + url);
String result = BonusPackHelper.requestStringFromUrl(url);
//log.debug(result);
if (result == null)
throw new IOException();
try {
JSONObject jResult = new JSONObject(result);
Address gAddress = buildAndroidAddress(jResult);
List<Address> list = new ArrayList<Address>();
list.add(gAddress);
return list;
} catch (JSONException e) {
throw new IOException();
}
}
public List<Address> getFromLocationName(String locationName, int maxResults,
double lowerLeftLatitude, double lowerLeftLongitude,
double upperRightLatitude, double upperRightLongitude)
throws IOException {
String url = mServiceUrl
+ "search?"
+ "format=json"
+ "&accept-language=" + mLocale.getLanguage()
+ "&addressdetails=1"
+ "&limit=" + maxResults
+ "&q=" + URLEncoder.encode(locationName, "UTF-8");
if (lowerLeftLatitude != 0.0 && lowerLeftLongitude != 0.0) {
//viewbox = left, top, right, bottom:
url += "&viewbox=" + lowerLeftLongitude
+ "," + upperRightLatitude
+ "," + upperRightLongitude
+ "," + lowerLeftLatitude
+ "&bounded=1";
}
log.debug("GeocoderNominatim::getFromLocationName:" + url);
String result = BonusPackHelper.requestStringFromUrl(url);
//log.debug(result);
if (result == null)
throw new IOException();
try {
JSONArray jResults = new JSONArray(result);
List<Address> list = new ArrayList<Address>();
for (int i = 0; i < jResults.length(); i++) {
JSONObject jResult = jResults.getJSONObject(i);
Address gAddress = buildAndroidAddress(jResult);
list.add(gAddress);
}
return list;
} catch (JSONException e) {
throw new IOException();
}
}
public List<Address> getFromLocationName(String locationName, int maxResults)
throws IOException {
return getFromLocationName(locationName, maxResults, 0.0, 0.0, 0.0, 0.0);
}
}

View File

@@ -0,0 +1,192 @@
package org.osmdroid.location;
import android.graphics.Bitmap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.oscim.core.BoundingBox;
import org.oscim.core.GeoPoint;
import org.osmdroid.utils.BonusPackHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.URLEncoder;
import java.util.ArrayList;
/**
* POI Provider using Nominatim service. <br>
* See https://wiki.openstreetmap.org/wiki/Nominatim<br>
* and http://open.mapquestapi.com/nominatim/<br>
*
* @author M.Kergall
*/
public class NominatimPOIProvider implements POIProvider {
final static Logger log = LoggerFactory.getLogger(NominatimPOIProvider.class);
/* As the doc lacks a lot of features, source code may help:
* https://trac.openstreetmap
* .org/browser/applications/utils/nominatim/website/search.php featuretype=
* to select on feature type (country, city, state, settlement)<br>
* format=jsonv2 to get a place_rank<br> offset= to offset the result ?...
* <br> polygon=1 to get the border of the poi as a polygon<br> nearlat &
* nearlon = ???<br> routewidth/69 and routewidth/30 ???<br> */
public static final String MAPQUEST_POI_SERVICE = "http://open.mapquestapi.com/nominatim/v1/";
public static final String NOMINATIM_POI_SERVICE = "http://nominatim.openstreetmap.org/";
protected String mService;
public NominatimPOIProvider() {
mService = NOMINATIM_POI_SERVICE;
}
public void setService(String serviceUrl) {
mService = serviceUrl;
}
@SuppressWarnings("deprecation")
private StringBuffer getCommonUrl(String type, int maxResults) {
StringBuffer urlString = new StringBuffer(mService);
urlString.append("search?");
urlString.append("format=json");
urlString.append("&q=" + URLEncoder.encode(type));
urlString.append("&limit=" + maxResults);
//urlString.append("&bounded=1");
// urlString.append("&addressdetails=0");
return urlString;
}
private String getUrlInside(BoundingBox bb, String type, int maxResults) {
StringBuffer urlString = getCommonUrl(type, maxResults);
urlString.append("&viewbox=" + bb.getMaxLongitude() + ","
+ bb.getMaxLatitude() + ","
+ bb.getMinLongitude() + ","
+ bb.getMinLatitude());
return urlString.toString();
}
private String getUrlCloseTo(GeoPoint p, String type,
int maxResults, double maxDistance) {
int maxD = (int) (maxDistance * 1E6);
BoundingBox bb = new BoundingBox(p.latitudeE6 + maxD,
p.longitudeE6 + maxD,
p.latitudeE6 - maxD,
p.longitudeE6 - maxD);
return getUrlInside(bb, type, maxResults);
}
/**
* @param url full URL request
* @return the list of POI, of null if technical issue.
*/
public ArrayList<POI> getThem(String url) {
log.debug("NominatimPOIProvider:get:" + url);
String jString = BonusPackHelper.requestStringFromUrl(url);
if (jString == null) {
log.error("NominatimPOIProvider: request failed.");
return null;
}
try {
JSONArray jPlaceIds = new JSONArray(jString);
int n = jPlaceIds.length();
ArrayList<POI> pois = new ArrayList<POI>(n);
Bitmap thumbnail = null;
for (int i = 0; i < n; i++) {
JSONObject jPlace = jPlaceIds.getJSONObject(i);
POI poi = new POI(POI.POI_SERVICE_NOMINATIM);
poi.id = jPlace.getString("osm_id");
// jPlace.optLong("osm_id");
poi.location = new GeoPoint(jPlace.getDouble("lat"), jPlace.getDouble("lon"));
JSONArray bbox = jPlace.optJSONArray("boundingbox");
if (bbox != null) {
try {
poi.bbox = new BoundingBox(bbox.getDouble(0), bbox.getDouble(2),
bbox.getDouble(1), bbox.getDouble(3));
} catch (Exception e) {
log.debug("could not parse " + bbox);
}
//log.debug("bbox " + poi.bbox);
}
poi.category = jPlace.optString("class");
poi.type = jPlace.getString("type");
poi.description = jPlace.optString("display_name");
poi.thumbnailPath = jPlace.optString("icon", null);
if (i == 0 && poi.thumbnailPath != null) {
//first POI, and we have a thumbnail: load it
thumbnail = BonusPackHelper.loadBitmap(poi.thumbnailPath);
}
poi.thumbnail = thumbnail;
pois.add(poi);
}
return pois;
} catch (JSONException e) {
e.printStackTrace();
return null;
}
}
/**
* @param position ...
* @param type an OpenStreetMap feature. See
* http://wiki.openstreetmap.org/wiki/Map_Features or
* http://code.google.com/p/osmbonuspack/source/browse/trunk/
* OSMBonusPackDemo/res/values/poi_tags.xml
* @param maxResults the maximum number of POI returned. Note that in any case,
* Nominatim will have an absolute maximum of 100.
* @param maxDistance to the position, in degrees. Note that it is used to build a
* bounding box around the position, not a circle.
* @return the list of POI, null if technical issue.
*/
public ArrayList<POI> getPOICloseTo(GeoPoint position, String type,
int maxResults, double maxDistance) {
String url = getUrlCloseTo(position, type, maxResults, maxDistance);
return getThem(url);
}
/**
* @param boundingBox ...
* @param type OpenStreetMap feature
* @param maxResults ...
* @return list of POIs, null if technical issue.
*/
public ArrayList<POI> getPOIInside(BoundingBox boundingBox, String type, int maxResults) {
String url = getUrlInside(boundingBox, type, maxResults);
return getThem(url);
}
public ArrayList<POI> getPOI(String query, int maxResults) {
String url = getCommonUrl(query, maxResults).toString();
return getThem(url);
}
/**
* @param path Warning: a long path may cause a failure due to the url to be
* too long. Using a simplified route may help (see
* Road.getRouteLow()).
* @param type OpenStreetMap feature
* @param maxResults ...
* @param maxWidth to the path. Certainly not in degrees. Probably in km.
* @return list of POIs, null if technical issue.
*/
public ArrayList<POI> getPOIAlong(ArrayList<GeoPoint> path, String type,
int maxResults, double maxWidth) {
StringBuffer urlString = getCommonUrl(type, maxResults);
urlString.append("&routewidth=" + maxWidth);
urlString.append("&route=");
boolean isFirst = true;
for (GeoPoint p : path) {
if (isFirst)
isFirst = false;
else
urlString.append(",");
String lat = Double.toString(p.getLatitude());
lat = lat.substring(0, Math.min(lat.length(), 7));
String lon = Double.toString(p.getLongitude());
lon = lon.substring(0, Math.min(lon.length(), 7));
urlString.append(lat + "," + lon);
//limit the size of url as much as possible, as post method is not supported.
}
return getThem(urlString.toString());
}
}

View File

@@ -0,0 +1,67 @@
package org.osmdroid.location;
import org.oscim.core.BoundingBox;
import org.oscim.core.GeoPoint;
import org.oscim.core.Tag;
import org.oscim.core.osm.OsmData;
import org.oscim.core.osm.OsmNode;
import org.oscim.utils.osmpbf.OsmPbfReader;
import org.osmdroid.utils.HttpConnection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
public class OverpassPOIProvider implements POIProvider {
final static Logger log = LoggerFactory
.getLogger(OverpassPOIProvider.class);
public static final String TAG_KEY_WEBSITE = "website".intern();
@Override
public List<POI> getPOIInside(BoundingBox boundingBox, String query,
int maxResults) {
HttpConnection connection = new HttpConnection();
boundingBox.toString();
String q = "node[\"amenity\"~\"^restaurant$|^pub$\"]("
+ boundingBox.format() + ");out 100;";
String url = "http://city.informatik.uni-bremen.de/oapi/pbf?data=";
String encoded;
try {
encoded = URLEncoder.encode(q, "utf-8");
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
return null;
}
log.debug("request " + url + encoded);
connection.doGet(url + encoded);
OsmData osmData = OsmPbfReader.process(connection.getStream());
ArrayList<POI> pois = new ArrayList<POI>(osmData.getNodes().size());
for (OsmNode n : osmData.getNodes()) {
POI p = new POI(POI.POI_SERVICE_4SQUARE);
p.id = Long.toString(n.id);
p.location = new GeoPoint(n.lat, n.lon);
Tag t;
if ((t = n.tags.get(Tag.KEY_NAME)) != null)
p.description = t.value;
if ((t = n.tags.get(Tag.KEY_AMENITY)) != null)
p.type = t.value;
if ((t = n.tags.get(TAG_KEY_WEBSITE)) != null) {
log.debug(p.description + " " + t.value);
p.url = t.value;
}
pois.add(p);
}
return pois;
}
}

View File

@@ -0,0 +1,205 @@
package org.osmdroid.location;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.view.View;
import android.widget.ImageView;
import org.oscim.app.R;
import org.oscim.core.BoundingBox;
import org.oscim.core.GeoPoint;
import org.osmdroid.utils.BonusPackHelper;
/**
* Point of Interest. Exact content may depend of the POI provider used.
*
* @author M.Kergall
* @see NominatimPOIProvider
* @see GeoNamesPOIProvider
*/
public class POI {
/**
* IDs of POI services
*/
public static int POI_SERVICE_NOMINATIM = 100;
public static int POI_SERVICE_GEONAMES_WIKIPEDIA = 200;
public static int POI_SERVICE_FLICKR = 300;
public static int POI_SERVICE_PICASA = 400;
public static int POI_SERVICE_4SQUARE = 500;
/**
* Identifies the service provider of this POI.
*/
public int serviceId;
/**
* Nominatim: OSM ID. GeoNames: 0
*/
public String id;
/**
* location of the POI
*/
public GeoPoint location;
public BoundingBox bbox;
/**
* Nominatim "class", GeoNames "feature"
*/
public String category;
/**
* type or title
*/
public String type;
/**
* can be the name, the address, a short description
*/
public String description;
/**
* url of the thumbnail. Null if none
*/
public String thumbnailPath;
/**
* the thumbnail itself. Null if none
*/
public Bitmap thumbnail;
/**
* url to a more detailed information page about this POI. Null if none
*/
public String url;
/**
* popularity of this POI, from 1 (lowest) to 100 (highest). 0 if not
* defined.
*/
public int rank;
/**
* number of attempts to load the thumbnail that have failed
*/
protected int mThumbnailLoadingFailures;
public POI(int serviceId) {
this.serviceId = serviceId;
// lets all other fields empty or null. That's fine.
}
protected static int MAX_LOADING_ATTEMPTS = 2;
/**
* @return the POI thumbnail as a Bitmap, if any. If not done yet, it will
* load the POI thumbnail from its url (in thumbnailPath field).
*/
public Bitmap getThumbnail() {
if (thumbnail == null && thumbnailPath != null) {
thumbnail = BonusPackHelper.loadBitmap(thumbnailPath);
if (thumbnail == null) {
mThumbnailLoadingFailures++;
if (mThumbnailLoadingFailures >= MAX_LOADING_ATTEMPTS) {
// this path really doesn't work, "kill" it for next calls:
thumbnailPath = null;
}
}
}
return thumbnail;
}
// http://stackoverflow.com/questions/7729133/using-asynctask-to-load-images-in-listview
// TODO see link, there might be a better solution
/**
* Fetch the thumbnail from its url on a thread.
*
* @param imageView to update once the thumbnail is retrieved, or to hide if no
* thumbnail.
*/
public void fetchThumbnail(final ImageView imageView) {
if (thumbnail != null) {
imageView.setImageBitmap(thumbnail);
imageView.setVisibility(View.VISIBLE);
} else if (thumbnailPath != null) {
imageView.setImageResource(R.drawable.ic_empty);
imageView.setVisibility(View.VISIBLE);
new ThumbnailTask(imageView).execute(imageView);
} else {
imageView.setVisibility(View.GONE);
}
}
class ThumbnailTask extends AsyncTask<ImageView, Void, ImageView> {
public ThumbnailTask(ImageView iv) {
iv.setTag(thumbnailPath);
}
@Override
protected ImageView doInBackground(ImageView... params) {
getThumbnail();
return params[0];
}
@Override
protected void onPostExecute(ImageView iv) {
if (iv == null || thumbnail == null)
return;
if (thumbnailPath.equals(iv.getTag().toString()))
iv.setImageBitmap(thumbnail);
}
}
// --- Parcelable implementation
// @Override
// public int describeContents() {
// return 0;
// }
// @Override
// public void writeToParcel(Parcel out, int flags) {
// out.writeInt(serviceId);
// out.writeString(id);
// out.writeParcelable(location, 0);
// out.writeString(category);
// out.writeString(type);
// out.writeString(description);
// out.writeString(thumbnailPath);
// out.writeParcelable(thumbnail, 0);
// out.writeString(url);
// out.writeInt(rank);
// out.writeInt(mThumbnailLoadingFailures);
// }
//
// public static final Parcelable.Creator<POI> CREATOR = new Parcelable.Creator<POI>() {
// @Override
// public POI createFromParcel(Parcel in) {
// POI poi = new POI(in.readInt());
// poi.id = in.readString();
// poi.location = in.readParcelable(GeoPoint.class.getClassLoader());
// poi.category = in.readString();
// poi.type = in.readString();
// poi.description = in.readString();
// poi.thumbnailPath = in.readString();
// poi.thumbnail = in.readParcelable(Bitmap.class.getClassLoader());
// poi.url = in.readString();
// poi.rank = in.readInt();
// poi.mThumbnailLoadingFailures = in.readInt();
// return poi;
// }
//
// @Override
// public POI[] newArray(int size) {
// return new POI[size];
// }
// };
// private POI(Parcel in) {
// serviceId = in.readInt();
// id = in.readLong();
// location = in.readParcelable(GeoPoint.class.getClassLoader());
// category = in.readString();
// type = in.readString();
// description = in.readString();
// thumbnailPath = in.readString();
// thumbnail = in.readParcelable(Bitmap.class.getClassLoader());
// url = in.readString();
// rank = in.readInt();
// mThumbnailLoadingFailures = in.readInt();
// }
}

View File

@@ -0,0 +1,10 @@
package org.osmdroid.location;
import org.oscim.core.BoundingBox;
import java.util.List;
public interface POIProvider {
public List<POI> getPOIInside(BoundingBox boundingBox, String query, int maxResults);
}

View File

@@ -0,0 +1,161 @@
package org.osmdroid.location;
import org.oscim.core.BoundingBox;
import org.oscim.core.GeoPoint;
import org.osmdroid.utils.HttpConnection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
/**
* POI Provider using Picasa service.
*
* @author M.Kergall
* @see "https://developers.google.com/picasa-web/docs/2.0/reference"
*/
public class PicasaPOIProvider implements POIProvider {
final static Logger log = LoggerFactory.getLogger(PicasaPOIProvider.class);
String mAccessToken;
/**
* @param accessToken the account to give to the service. Null for public access.
* @see "https://developers.google.com/picasa-web/docs/2.0/developers_guide_protocol#CreatingAccount"
*/
public PicasaPOIProvider(String accessToken) {
mAccessToken = accessToken;
}
@SuppressWarnings("deprecation")
private String getUrlInside(BoundingBox boundingBox, int maxResults, String query) {
StringBuffer url = new StringBuffer("http://picasaweb.google.com/data/feed/api/all?");
url.append("bbox=" + boundingBox.getMinLongitude());
url.append("," + boundingBox.getMinLatitude());
url.append("," + boundingBox.getMaxLongitude());
url.append("," + boundingBox.getMaxLatitude());
url.append("&max-results=" + maxResults);
url.append("&thumbsize=64c"); //thumbnail size: 64, cropped.
url.append("&fields=openSearch:totalResults,entry(summary,media:group/media:thumbnail,media:group/media:title,gphoto:*,georss:where,link)");
if (query != null)
url.append("&q=" + URLEncoder.encode(query));
if (mAccessToken != null) {
//TODO: warning: not tested...
url.append("&access_token=" + mAccessToken);
}
return url.toString();
}
public ArrayList<POI> getThem(String fullUrl) {
log.debug("PicasaPOIProvider:get:" + fullUrl);
HttpConnection connection = new HttpConnection();
connection.doGet(fullUrl);
InputStream stream = connection.getStream();
if (stream == null) {
return null;
}
PicasaXMLHandler handler = new PicasaXMLHandler();
try {
SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
parser.getXMLReader().setFeature("http://xml.org/sax/features/namespaces", false);
parser.getXMLReader()
.setFeature("http://xml.org/sax/features/namespace-prefixes", true);
parser.parse(stream, handler);
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
connection.close();
if (handler.mPOIs != null)
log.debug("done:" + handler.mPOIs.size() + " got on a total of:"
+ handler.mTotalResults);
return handler.mPOIs;
}
/**
* @param boundingBox ...
* @param maxResults ...
* @param query - optional - full-text query string. Searches the title,
* caption and tags for the specified string value.
* @return list of POI, Picasa photos inside the bounding box. Null if
* technical issue.
*/
public List<POI> getPOIInside(BoundingBox boundingBox, String query, int maxResults) {
String url = getUrlInside(boundingBox, maxResults, query);
return getThem(url);
}
}
class PicasaXMLHandler extends DefaultHandler {
private String mString;
double mLat, mLng;
POI mPOI;
ArrayList<POI> mPOIs;
int mTotalResults;
public PicasaXMLHandler() {
mPOIs = new ArrayList<POI>();
}
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) {
if (qName.equals("entry")) {
mPOI = new POI(POI.POI_SERVICE_PICASA);
} else if (qName.equals("media:thumbnail")) {
mPOI.thumbnailPath = attributes.getValue("url");
} else if (qName.equals("link")) {
String rel = attributes.getValue("rel");
if ("http://schemas.google.com/photos/2007#canonical".equals(rel)) {
mPOI.url = attributes.getValue("href");
}
}
mString = new String();
}
@Override
public void characters(char[] ch, int start, int length) {
String chars = new String(ch, start, length);
mString = mString.concat(chars);
}
@Override
public void endElement(String uri, String localName, String qName) {
if (qName.equals("gml:pos")) {
String[] coords = mString.split(" ");
mLat = Double.parseDouble(coords[0]);
mLng = Double.parseDouble(coords[1]);
} else if (qName.equals("gphoto:id")) {
mPOI.id = mString;
} else if (qName.equals("media:title")) {
mPOI.type = mString;
} else if (qName.equals("summary")) {
mPOI.description = mString;
} else if (qName.equals("gphoto:albumtitle")) {
mPOI.category = mString;
} else if (qName.equals("entry")) {
mPOI.location = new GeoPoint(mLat, mLng);
mPOIs.add(mPOI);
mPOI = null;
} else if (qName.equals("openSearch:totalResults")) {
mTotalResults = Integer.parseInt(mString);
}
}
}

View File

@@ -0,0 +1,99 @@
package org.osmdroid.overlays;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import org.oscim.android.MapView;
import org.oscim.app.App;
import org.osmdroid.utils.BonusPackHelper;
/**
* Default implementation of InfoWindow. It handles a text and a description. It
* also handles optionally a sub-description and an image. Clicking on the
* bubble will close it.
*
* @author M.Kergall
*/
public class DefaultInfoWindow extends InfoWindow {
// resource ids
private static int mTitleId = 0, mDescriptionId = 0, mSubDescriptionId = 0, mImageId = 0;
private static void setResIds(Context context) {
// get application package name
String packageName = context.getPackageName();
Resources res = context.getResources();
mTitleId = res.getIdentifier("id/bubble_title", null, packageName);
mDescriptionId = res.getIdentifier("id/bubble_description", null, packageName);
mSubDescriptionId = res.getIdentifier("id/bubble_subdescription", null, packageName);
mImageId = res.getIdentifier("id/bubble_image", null, packageName);
if (mTitleId == 0 || mDescriptionId == 0) {
Log.e(BonusPackHelper.LOG_TAG, "DefaultInfoWindow: unable to get res ids in "
+ packageName);
}
}
public DefaultInfoWindow(int layoutResId, MapView mapView) {
super(layoutResId, mapView);
if (mTitleId == 0)
setResIds(App.activity);
// default behaviour: close it when clicking on the bubble:
mView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
close();
}
});
}
@Override
public void onOpen(ExtendedMarkerItem item) {
String title = item.getTitle();
if (title == null)
title = "";
((TextView) mView.findViewById(mTitleId)).setText(title);
String snippet = item.getDescription();
if (snippet == null)
snippet = "";
((TextView) mView.findViewById(mDescriptionId)).setText(snippet);
// handle sub-description, hidding or showing the text view:
TextView subDescText = (TextView) mView.findViewById(mSubDescriptionId);
String subDesc = item.getSubDescription();
if (subDesc != null && !("".equals(subDesc))) {
subDescText.setText(subDesc);
subDescText.setVisibility(View.VISIBLE);
} else {
subDescText.setVisibility(View.GONE);
}
// handle image
ImageView imageView = (ImageView) mView.findViewById(mImageId);
Drawable image = item.getImage();
if (image != null) {
// or setBackgroundDrawable(image)?
imageView.setImageDrawable(image);
imageView.setVisibility(View.VISIBLE);
} else
imageView.setVisibility(View.GONE);
}
@Override
public void onClose() {
// by default, do nothing
}
}

View File

@@ -0,0 +1,123 @@
package org.osmdroid.overlays;
import android.graphics.drawable.Drawable;
import org.oscim.core.GeoPoint;
import org.oscim.layers.marker.MarkerItem;
import org.oscim.map.Map;
/**
* An OverlayItem to use in ItemizedOverlayWithBubble<br>
* - more complete: can contain an image and a sub-description that will be
* displayed in the bubble, <br>
* - and flexible: attributes are modifiable<br>
* Known Issues:<br>
* - Bubble offset is not perfect on h&xhdpi resolutions, due to an osmdroid
* issue on marker drawing<br>
* - Bubble offset is at 0 when using the default marker => set the marker on
* each item!<br>
*
* @author M.Kergall
* @see ItemizedOverlayWithBubble
*/
public class ExtendedMarkerItem extends MarkerItem {
// now, they are modifiable
private String mTitle, mDescription;
// now, they are modifiable
// a third field that can be displayed in
// the infowindow, on a third line
// that will be shown in the infowindow.
//unfortunately, this is not so simple...
private String mSubDescription;
private Drawable mImage;
private Object mRelatedObject; // reference to an object (of any kind)
// linked to this item.
public ExtendedMarkerItem(String aTitle, String aDescription, GeoPoint aGeoPoint) {
super(aTitle, aDescription, aGeoPoint);
mTitle = aTitle;
mDescription = aDescription;
mSubDescription = null;
mImage = null;
mRelatedObject = null;
}
public void setTitle(String aTitle) {
mTitle = aTitle;
}
public void setDescription(String aDescription) {
mDescription = aDescription;
}
public void setSubDescription(String aSubDescription) {
mSubDescription = aSubDescription;
}
public void setImage(Drawable anImage) {
mImage = anImage;
}
public void setRelatedObject(Object o) {
mRelatedObject = o;
}
@Override
public String getTitle() {
return mTitle;
}
public String getDescription() {
return mDescription;
}
public String getSubDescription() {
return mSubDescription;
}
public Drawable getImage() {
return mImage;
}
public Object getRelatedObject() {
return mRelatedObject;
}
/**
* Populates this bubble with all item info:
* <ul>
* title and description in any case,
* </ul>
* <ul>
* image and sub-description if any.
* </ul>
* and centers the map on the item. <br>
*
* @param bubble ...
* @param map ...
*/
public void showBubble(InfoWindow bubble, Map map) {
// offset the bubble to be top-centered on the marker:
// Drawable marker = getMarker(0 /* OverlayItem.ITEM_STATE_FOCUSED_MASK */);
// int markerWidth = 0, markerHeight = 0;
// if (marker != null) {
// markerWidth = marker.getIntrinsicWidth();
// markerHeight = marker.getIntrinsicHeight();
// } // else... we don't have the default marker size => don't user default
// // markers!!!
// Point markerH = getHotspot(getMarkerHotspot(), markerWidth, markerHeight);
// Point bubbleH = getHotspot(HotspotPlace.TOP_CENTER, markerWidth, markerHeight);
// bubbleH.offset(-markerH.x, -markerH.y);
//
// bubble.open(this, bubbleH.x, bubbleH.y);
// OverlayMarker marker = getMarker();
// PointF hotspot = marker.getHotspot();
// Bitmap b = marker.getBitmap();
//bubble.open(this, (int)(-b.getWidth() * hotspot.x), (int)(-b.getHeight()));
//bubble.open(this, 0, (int)(b.getHeight()));
bubble.open(this, 0, 0);
}
}

View File

@@ -0,0 +1,135 @@
package org.osmdroid.overlays;
// TODO composite view as texture overlay and only allow one bubble at a time.
import android.content.Context;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import org.oscim.android.MapView;
/**
* View that can be displayed on an OSMDroid map, associated to a GeoPoint.
* Typical usage: cartoon-like bubbles displayed when clicking an overlay item.
* It mimics the InfoWindow class of Google Maps JavaScript API V3. Main
* differences are:
* <ul>
* <li>Structure and content of the view is let to the responsibility of the
* caller.</li>
* <li>The same InfoWindow can be associated to many items.</li>
* </ul>
* Known issues:
* <ul>
* <li>It disappears when zooming in/out (osmdroid issue #259 on osmdroid 3.0.8,
* should be fixed in next version).</li>
* <li>The window is displayed "above" the marker, so the queue of the bubble
* can hide the marker.</li>
* </ul>
* This is an abstract class.
*
* @author M.Kergall
* @see DefaultInfoWindow
*/
public abstract class InfoWindow {
protected View mView;
protected boolean mIsVisible = false;
protected RelativeLayout mLayout;
private android.widget.RelativeLayout.LayoutParams mLayoutPos;
private MapView mMap;
/**
* @param layoutResId the id of the view resource.
* @param mapView the mapview on which is hooked the view
*/
public InfoWindow(int layoutResId, MapView mapView) {
ViewGroup parent = (ViewGroup) mapView.getParent();
Context context = mapView.getContext();
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mView = inflater.inflate(layoutResId, parent, false);
RelativeLayout.LayoutParams rlp =
new RelativeLayout.LayoutParams(
android.view.ViewGroup.LayoutParams.MATCH_PARENT,
android.view.ViewGroup.LayoutParams.MATCH_PARENT);
mLayout = new RelativeLayout(context);
mLayout.setWillNotDraw(true);
mLayout.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM);
mLayout.setLayoutParams(rlp);
mLayoutPos = rlp;
mView.setDrawingCacheEnabled(true);
mLayout.addView(mView);
mIsVisible = false;
mLayout.setVisibility(View.GONE);
mMap = mapView;
parent.addView(mLayout);
}
/**
* Returns the Android view. This allows to set its content.
*
* @return the Android view
*/
public View getView() {
return (mView);
}
private int mHeight;
/**
* open the window at the specified position.
*
* @param item the item on which is hooked the view
* @param offsetX (&offsetY) the offset of the view to the position, in pixels.
* This allows to offset the view from the marker position.
* @param offsetY ...
*/
public void open(ExtendedMarkerItem item, int offsetX, int offsetY) {
onOpen(item);
close();
mView.buildDrawingCache();
mHeight = mMap.getHeight();
mLayout.setVisibility(View.VISIBLE);
mIsVisible = true;
}
public void position(int x, int y) {
RelativeLayout.LayoutParams rlp = mLayoutPos;
rlp.leftMargin = x;
rlp.rightMargin = -x;
rlp.topMargin = y;
rlp.bottomMargin = mHeight / 2 - y;
mLayout.setLayoutParams(rlp);
mLayout.requestLayout();
}
public void close() {
if (mIsVisible) {
mIsVisible = false;
mLayout.setVisibility(View.GONE);
onClose();
}
}
public boolean isOpen() {
return mIsVisible;
}
// Abstract methods to implement:
public abstract void onOpen(ExtendedMarkerItem item);
public abstract void onClose();
}

View File

@@ -0,0 +1,195 @@
package org.osmdroid.overlays;
import android.content.Context;
import android.util.Log;
import org.oscim.app.App;
import org.oscim.core.GeoPoint;
import org.oscim.core.MapPosition;
import org.oscim.core.Point;
import org.oscim.event.Event;
import org.oscim.event.MotionEvent;
import org.oscim.layers.marker.ItemizedLayer;
import org.oscim.layers.marker.MarkerItem;
import org.oscim.layers.marker.MarkerSymbol;
import org.oscim.map.Map;
import org.osmdroid.utils.BonusPackHelper;
import java.util.List;
/**
* An itemized overlay with an InfoWindow or "bubble" which opens when the user
* taps on an overlay item, and displays item attributes. <br>
* Items must be ExtendedMarkerItem. <br>
*
* @param <Item> ...
* @author M.Kergall
* @see ExtendedMarkerItem
* @see InfoWindow
*/
public class ItemizedOverlayWithBubble<Item extends MarkerItem> extends
ItemizedLayer<Item> implements
ItemizedLayer.OnItemGestureListener<Item>, Map.UpdateListener {
/* only one for all items of this overlay => one at a time */
protected InfoWindow mBubble;
/* the item currently showing the bubble. Null if none. */
protected MarkerItem mItemWithBubble;
static int layoutResId = 0;
public ItemizedOverlayWithBubble(Map map, Context context,
MarkerSymbol marker, List<Item> list, InfoWindow bubble) {
super(map, list, marker, null);
if (bubble != null) {
mBubble = bubble;
} else {
// build default bubble:
String packageName = context.getPackageName();
if (layoutResId == 0) {
layoutResId = context.getResources().getIdentifier(
"layout/bonuspack_bubble",
null,
packageName);
if (layoutResId == 0)
Log.e(BonusPackHelper.LOG_TAG,
"ItemizedOverlayWithBubble: layout/bonuspack_bubble not found in "
+ packageName);
}
mBubble = new DefaultInfoWindow(layoutResId, App.view);
}
mItemWithBubble = null;
mOnItemGestureListener = this;
}
public ItemizedOverlayWithBubble(Map map, Context context,
MarkerSymbol marker, List<Item> aList) {
this(map, context, marker, aList, null);
}
@Override
public boolean onItemLongPress(int index, MarkerItem item) {
if (mBubble.isOpen())
hideBubble();
else
showBubble(index);
return false;
}
@Override
public boolean onItemSingleTapUp(int index, MarkerItem item) {
showBubble(index);
return true;
}
private final Point mTmpPoint = new Point();
@Override
protected boolean activateSelectedItems(MotionEvent event, ActiveItem task) {
boolean hit = super.activateSelectedItems(event, task);
if (!hit)
hideBubble();
return hit;
}
@Override
public void onMapEvent(Event e, MapPosition mapPosition) {
if (mBubble.isOpen()) {
GeoPoint gp = mItemWithBubble.getPoint();
Point p = mTmpPoint;
mMap.viewport().toScreenPoint(gp, p);
mBubble.position((int) p.x, (int) p.y);
}
}
void showBubble(int index) {
showBubbleOnItem(index);
}
/**
* Opens the bubble on the item. For each ItemizedOverlay, only one bubble
* is opened at a time. If you want more bubbles opened simultaneously, use
* many ItemizedOverlays.
*
* @param index of the overlay item to show
*/
@SuppressWarnings("unchecked")
public void showBubbleOnItem(int index) {
ExtendedMarkerItem item = (ExtendedMarkerItem) (mItemList.get(index));
mItemWithBubble = item;
if (item != null) {
item.showBubble(mBubble, (Map) mMap);
mMap.animator().animateTo(item.geoPoint);
mMap.updateMap(true);
setFocus((Item) item);
}
}
/**
* Close the bubble (if it's opened).
*/
public void hideBubble() {
mBubble.close();
mItemWithBubble = null;
}
// @Override
// public boolean onSingleTapUp(final MotionEvent event) {
// boolean handled = super.onSingleTapUp(event);
// if (!handled)
// hideBubble();
// return handled;
// }
//
// @Override
// protected boolean onSingleTapUpHelper(final int index, final Item item) {
// showBubbleOnItem(index);
// return true;
// }
/**
* @return the item currenty showing the bubble, or null if none.
*/
public MarkerItem getBubbledItem() {
if (mBubble.isOpen())
return mItemWithBubble;
return null;
}
/**
* @return the index of the item currenty showing the bubble, or -1 if none.
*/
public int getBubbledItemId() {
MarkerItem item = getBubbledItem();
if (item == null)
return -1;
return mItemList.indexOf(item);
}
@Override
public boolean removeItem(final Item item) {
boolean result = super.removeItem(item);
if (mItemWithBubble == item) {
hideBubble();
}
return result;
}
@Override
public void removeAllItems() {
super.removeAllItems();
hideBubble();
}
}

View File

@@ -0,0 +1,34 @@
package org.osmdroid.overlays;
import org.oscim.core.GeoPoint;
/**
* Interface for objects that need to handle map events thrown by a
* MapEventsOverlay.
*
* @author M.Kergall
*/
public interface MapEventsReceiver {
/**
* @param p the position where the event occurred.
* @return true if the event has been "consumed" and should not be handled
* by other objects.
*/
boolean singleTapUpHelper(GeoPoint p);
/**
* @param p the position where the event occurred.
* @return true if the event has been "consumed" and should not be handled
* by other objects.
*/
boolean longPressHelper(GeoPoint p);
/**
* @param p1 p2
* the position where the event occurred for 2 finger.
* @return true if the event has been "consumed" and should not be handled
* by other objects.
*/
boolean longPressHelper(GeoPoint p1, GeoPoint p2);
}

View File

@@ -0,0 +1,255 @@
package org.osmdroid.routing;
import org.oscim.core.BoundingBox;
import org.oscim.core.GeoPoint;
import org.osmdroid.routing.provider.GoogleRouteProvider;
import org.osmdroid.routing.provider.MapQuestRouteProvider;
import org.osmdroid.routing.provider.OSRMRouteProvider;
import org.osmdroid.utils.DouglasPeuckerReducer;
import java.util.ArrayList;
import java.util.List;
/**
* describes the way to go from a position to an other. Normally returned by a
* call to a Directions API (from MapQuest, GoogleMaps or other)
*
* @author M.Kergall
* @see MapQuestRouteProvider
* @see GoogleRouteProvider
* @see OSRMRouteProvider
*/
public class Route {
//final static Logger log = LoggerFactory.getLogger(Route.class);
/**
* @see #STATUS_INVALID STATUS_INVALID
* @see #STATUS_OK STATUS_OK
* @see #STATUS_DEFAULT STATUS_DEFAULT
*/
public int status;
/**
* length of the whole route in km.
*/
public double length;
/**
* duration of the whole trip in sec.
*/
public double duration;
public List<RouteNode> nodes;
/** */
/**
* there is one leg between each waypoint
*/
public List<RouteLeg> legs;
/**
* full shape: polyline, as an array of GeoPoints
*/
public List<GeoPoint> routeHigh;
/**
* the same, in low resolution (less points)
*/
private List<GeoPoint> routeLow;
/**
* route bounding box
*/
public BoundingBox boundingBox;
/**
* STATUS_INVALID = route not built
*/
public static final int STATUS_INVALID = 0;
/**
* STATUS_OK = route properly retrieved and built
*/
public static final int STATUS_OK = 1;
/**
* STATUS_DEFAULT = any issue (technical issue, or no possible route) led to
* build a default route
*/
public static final int STATUS_DEFAULT = 2;
private void init() {
status = STATUS_INVALID;
length = 0.0;
duration = 0.0;
nodes = new ArrayList<RouteNode>();
routeHigh = new ArrayList<GeoPoint>();
routeLow = null;
legs = new ArrayList<RouteLeg>();
boundingBox = null;
}
public Route() {
init();
}
/**
* default constructor when normal loading failed: the route shape only
* contains the waypoints; All distances and times are at 0; there is no
* node; status equals DEFAULT.
*
* @param waypoints ...
*/
public Route(List<GeoPoint> waypoints) {
init();
int n = waypoints.size();
for (int i = 0; i < n; i++) {
GeoPoint p = waypoints.get(i);
routeHigh.add(p);
}
for (int i = 0; i < n - 1; i++) {
RouteLeg leg = new RouteLeg(/* i, i+1, mLinks */);
legs.add(leg);
}
boundingBox = BoundingBox.fromGeoPoints(routeHigh);
status = STATUS_DEFAULT;
}
/**
* @return the route shape in "low resolution" = simplified by around 10
* factor.
*/
public List<GeoPoint> getRouteLow() {
if (routeLow == null) {
// Simplify the route (divide number of points by around 10):
//int n = routeHigh.size();
routeLow = DouglasPeuckerReducer.reduceWithTolerance(routeHigh, 1500.0);
//log.debug("route reduced from " + n + " to " + routeLow.size()
// + " points");
}
return routeLow;
}
public void setRouteLow(ArrayList<GeoPoint> route) {
routeLow = route;
}
/**
* @param pLength in km
* @param pDuration in sec
* @return a human-readable length&duration text.
*/
public String getLengthDurationText(double pLength, double pDuration) {
String result;
if (pLength >= 100.0) {
result = (int) (pLength) + " km, ";
} else if (pLength >= 1.0) {
result = Math.round(pLength * 10) / 10.0 + " km, ";
} else {
result = (int) (pLength * 1000) + " m, ";
}
int totalSeconds = (int) pDuration;
int hours = totalSeconds / 3600;
int minutes = (totalSeconds / 60) - (hours * 60);
int seconds = (totalSeconds % 60);
if (hours != 0) {
result += hours + " h ";
}
if (minutes != 0) {
result += minutes + " min";
}
if (hours == 0 && minutes == 0) {
result += seconds + " s";
}
return result;
}
/**
* @param leg leg index, starting from 0. -1 for the whole route
* @return length and duration of the whole route, or of a leg of the route,
* as a String, in a readable format.
*/
public String getLengthDurationText(int leg) {
double len = (leg == -1 ? this.length : legs.get(leg).length);
double dur = (leg == -1 ? this.duration : legs.get(leg).duration);
return getLengthDurationText(len, dur);
}
protected double distanceLLSquared(GeoPoint p1, GeoPoint p2) {
double deltaLat = p2.latitudeE6 - p1.latitudeE6;
double deltaLon = p2.longitudeE6 - p1.longitudeE6;
return (deltaLat * deltaLat + deltaLon * deltaLon);
}
/**
* As MapQuest and OSRM doesn't provide legs information, we have to rebuild
* it, using the waypoints and the route nodes. <br>
* Note that MapQuest legs fit well with waypoints, as there is a
* "dedicated" node for each waypoint. But OSRM legs are not precise, as
* there is no node "dedicated" to waypoints.
*
* @param waypoints ...
*/
public void buildLegs(List<GeoPoint> waypoints) {
legs = new ArrayList<RouteLeg>();
int firstNodeIndex = 0;
// For all intermediate waypoints, search the node closest to the
// waypoint
int w = waypoints.size();
int n = nodes.size();
for (int i = 1; i < w - 1; i++) {
GeoPoint waypoint = waypoints.get(i);
double distanceMin = -1.0;
int nodeIndexMin = -1;
for (int j = firstNodeIndex; j < n; j++) {
GeoPoint routePoint = nodes.get(j).location;
double dSquared = distanceLLSquared(routePoint, waypoint);
if (nodeIndexMin == -1 || dSquared < distanceMin) {
distanceMin = dSquared;
nodeIndexMin = j;
}
}
// Build the leg as ending with this closest node:
RouteLeg leg = new RouteLeg(firstNodeIndex, nodeIndexMin, nodes);
legs.add(leg);
firstNodeIndex = nodeIndexMin + 1; // restart next leg from end
}
// Build last leg ending with last node:
RouteLeg lastLeg = new RouteLeg(firstNodeIndex, n - 1, nodes);
legs.add(lastLeg);
}
// --- Parcelable implementation
// @Override
// public int describeContents() {
// return 0;
// }
//
// @Override
// public void writeToParcel(Parcel out, int flags) {
// out.writeInt(status);
// out.writeDouble(length);
// out.writeDouble(duration);
// out.writeList(nodes);
// out.writeList(legs);
// out.writeList(routeHigh);
// out.writeParcelable(boundingBox, 0);
// }
//
// public static final Parcelable.Creator<Route> CREATOR = new Parcelable.Creator<Route>() {
// @Override
// public Route createFromParcel(Parcel source) {
// return new Route(source);
// }
//
// @Override
// public Route[] newArray(int size) {
// return new Route[size];
// }
// };
//
// @SuppressWarnings("unchecked")
// private Route(Parcel in) {
// status = in.readInt();
// length = in.readDouble();
// duration = in.readDouble();
//
// nodes = in.readArrayList(RouteNode.class.getClassLoader());
// legs = in.readArrayList(RouteLeg.class.getClassLoader());
// routeHigh = in.readArrayList(GeoPoint.class.getClassLoader());
// boundingBox = in.readParcelable(BoundingBox.class.getClassLoader());
// }
}

View File

@@ -0,0 +1,85 @@
package org.osmdroid.routing;
import android.os.Parcel;
import android.os.Parcelable;
import java.util.List;
/**
* Road Leg is the portion of the route between 2 waypoints (intermediate points
* requested)
*
* @author M.Kergall
*/
public class RouteLeg implements Parcelable {
//final static Logger log = LoggerFactory.getLogger(RouteLeg.class);
/**
* in km
*/
public double length;
/**
* in sec
*/
public double duration;
/**
* starting node of the leg, as index in nodes array
*/
public int startNodeIndex;
/**
* and ending node
*/
public int endNodeIndex;
public RouteLeg() {
length = duration = 0.0;
startNodeIndex = endNodeIndex = 0;
}
public RouteLeg(int startNodeIndex, int endNodeIndex,
List<RouteNode> nodes) {
this.startNodeIndex = startNodeIndex;
this.endNodeIndex = endNodeIndex;
length = duration = 0.0;
for (int i = startNodeIndex; i <= endNodeIndex; i++) {
RouteNode node = nodes.get(i);
length += node.length;
duration += node.duration;
}
//log.debug("Leg: " + startNodeIndex + "-" + endNodeIndex
// + ", length=" + length + "km, duration=" + duration + "s");
}
//--- Parcelable implementation
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel out, int flags) {
out.writeDouble(length);
out.writeDouble(duration);
out.writeInt(startNodeIndex);
out.writeInt(endNodeIndex);
}
public static final Parcelable.Creator<RouteLeg> CREATOR = new Parcelable.Creator<RouteLeg>() {
@Override
public RouteLeg createFromParcel(Parcel in) {
RouteLeg rl = new RouteLeg();
rl.length = in.readDouble();
rl.duration = in.readDouble();
rl.startNodeIndex = in.readInt();
rl.endNodeIndex = in.readInt();
return rl;
}
@Override
public RouteLeg[] newArray(int size) {
return new RouteLeg[size];
}
};
}

View File

@@ -0,0 +1,79 @@
package org.osmdroid.routing;
import org.oscim.core.GeoPoint;
/**
* Route intersection, with instructions to continue.
*
* @author M.Kergall
*/
public class RouteNode {
/**
* @see <a
* href="http://open.mapquestapi.com/guidance/#maneuvertypes">Maneuver
* Types</a>
*/
public int maneuverType;
/**
* textual information on what to do at this intersection
*/
public String instructions;
/**
* index in route links array - internal use only, for MapQuest directions
*/
public int nextRouteLink;
/**
* in km to the next node
*/
public double length;
/**
* in seconds to the next node
*/
public double duration;
/**
* position of the node
*/
public GeoPoint location;
public RouteNode() {
maneuverType = 0;
nextRouteLink = -1;
length = duration = 0.0;
}
// --- Parcelable implementation
// @Override
// public int describeContents() {
// return 0;
// }
//
// @Override
// public void writeToParcel(Parcel out, int flags) {
// out.writeInt(maneuverType);
// out.writeString(instructions);
// out.writeDouble(length);
// out.writeDouble(duration);
// out.writeParcelable(location, 0);
// }
//
// public static final Parcelable.Creator<RouteNode> CREATOR = new
// Parcelable.Creator<RouteNode>() {
// @Override
// public RouteNode createFromParcel(Parcel in) {
// RouteNode rn = new RouteNode();
// rn.maneuverType = in.readInt();
// rn.instructions = in.readString();
// rn.length = in.readDouble();
// rn.duration = in.readDouble();
// rn.location = in.readParcelable(GeoPoint.class.getClassLoader());
// return rn;
// }
//
// @Override
// public RouteNode[] newArray(int size) {
// return new RouteNode[size];
// }
// };
}

View File

@@ -0,0 +1,67 @@
package org.osmdroid.routing;
import org.oscim.core.GeoPoint;
import org.oscim.layers.PathLayer;
import org.oscim.map.Map;
import org.osmdroid.routing.provider.GoogleRouteProvider;
import org.osmdroid.routing.provider.MapQuestRouteProvider;
import org.osmdroid.routing.provider.OSRMRouteProvider;
import java.util.List;
/**
* Generic class to get a route between a start and a destination point, going
* through a list of waypoints.
*
* @author M.Kergall
* @see MapQuestRouteProvider
* @see GoogleRouteProvider
* @see OSRMRouteProvider
*/
public abstract class RouteProvider {
protected String mOptions;
public abstract Route getRoute(List<GeoPoint> waypoints);
public RouteProvider() {
mOptions = "";
}
/**
* Add an option that will be used in the route request. Note that some
* options are set in the request in all cases.
*
* @param requestOption see provider documentation. Just one example:
* "routeType=bicycle" for MapQuest; "mode=bicycling" for Google.
*/
public void addRequestOption(String requestOption) {
mOptions += "&" + requestOption;
}
protected String geoPointAsString(GeoPoint p) {
StringBuffer result = new StringBuffer();
double d = p.getLatitude();
result.append(Double.toString(d));
d = p.getLongitude();
result.append("," + Double.toString(d));
return result.toString();
}
/**
* Builds an overlay for the route shape with a default (and nice!) color.
*
* @return route shape overlay
*/
public static PathLayer buildRouteOverlay(Map map, Route route) {
int lineColor = 0x800000FF;
float lineWidth = 2.5f;
PathLayer routeOverlay = new PathLayer(map, lineColor, lineWidth);
if (route != null) {
routeOverlay.setPoints(route.routeHigh);
}
return routeOverlay;
}
}

View File

@@ -0,0 +1,235 @@
package org.osmdroid.routing.provider;
import org.oscim.core.BoundingBox;
import org.oscim.core.GeoPoint;
import org.osmdroid.routing.Route;
import org.osmdroid.routing.RouteLeg;
import org.osmdroid.routing.RouteNode;
import org.osmdroid.routing.RouteProvider;
import org.osmdroid.utils.HttpConnection;
import org.osmdroid.utils.PolylineEncoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
/**
* class to get a route between a start and a destination point, going through a
* list of waypoints. <br>
* https://developers.google.com/maps/documentation/directions/<br>
* Note that displaying a route provided by Google on a non-Google map (like
* OSM) is not allowed by Google T&C.
*
* @author M.Kergall
*/
public class GoogleRouteProvider extends RouteProvider {
final static Logger log = LoggerFactory.getLogger(GoogleRouteProvider.class);
static final String GOOGLE_DIRECTIONS_SERVICE = "http://maps.googleapis.com/maps/api/directions/xml?";
/**
* Build the URL to Google Directions service returning a route in XML
* format
*
* @param waypoints ...
* @return ...
*/
protected String getUrl(List<GeoPoint> waypoints) {
StringBuffer urlString = new StringBuffer(GOOGLE_DIRECTIONS_SERVICE);
urlString.append("origin=");
GeoPoint p = waypoints.get(0);
urlString.append(geoPointAsString(p));
urlString.append("&destination=");
int destinationIndex = waypoints.size() - 1;
p = waypoints.get(destinationIndex);
urlString.append(geoPointAsString(p));
for (int i = 1; i < destinationIndex; i++) {
if (i == 1)
urlString.append("&waypoints=");
else
urlString.append("%7C"); // the pipe (|), url-encoded
p = waypoints.get(i);
urlString.append(geoPointAsString(p));
}
urlString.append("&units=metric&sensor=false");
Locale locale = Locale.getDefault();
urlString.append("&language=" + locale.getLanguage());
urlString.append(mOptions);
return urlString.toString();
}
/**
* @param waypoints : list of GeoPoints. Must have at least 2 entries, start and
* end points.
* @return the route
*/
@Override
public Route getRoute(List<GeoPoint> waypoints) {
String url = getUrl(waypoints);
log.debug("GoogleRouteManager.getRoute:" + url);
Route route = null;
HttpConnection connection = new HttpConnection();
connection.doGet(url);
InputStream stream = connection.getStream();
if (stream != null)
route = getRouteXML(stream);
connection.close();
if (route == null || route.routeHigh.size() == 0) {
//Create default route:
route = new Route(waypoints);
} else {
//finalize route data update:
for (RouteLeg leg : route.legs) {
route.duration += leg.duration;
route.length += leg.length;
}
route.status = Route.STATUS_OK;
}
log.debug("GoogleRouteManager.getRoute - finished");
return route;
}
protected Route getRouteXML(InputStream is) {
GoogleDirectionsHandler handler = new GoogleDirectionsHandler();
try {
SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
parser.parse(is, handler);
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return handler.mRoute;
}
}
class GoogleDirectionsHandler extends DefaultHandler {
Route mRoute;
RouteLeg mLeg;
RouteNode mNode;
boolean isPolyline, isOverviewPolyline, isLeg, isStep, isDuration, isDistance, isBB;
int mValue;
double mLat, mLng;
double mNorth, mWest, mSouth, mEast;
private String mString;
public GoogleDirectionsHandler() {
isOverviewPolyline = isBB = isPolyline = isLeg = isStep = isDuration = isDistance = false;
mRoute = new Route();
}
@Override
public void startElement(String uri, String localName, String name,
Attributes attributes) {
if (localName.equals("polyline")) {
isPolyline = true;
} else if (localName.equals("overview_polyline")) {
isOverviewPolyline = true;
} else if (localName.equals("leg")) {
mLeg = new RouteLeg();
isLeg = true;
} else if (localName.equals("step")) {
mNode = new RouteNode();
isStep = true;
} else if (localName.equals("duration")) {
isDuration = true;
} else if (localName.equals("distance")) {
isDistance = true;
} else if (localName.equals("bounds")) {
isBB = true;
}
mString = new String();
}
/**
* Overrides org.xml.sax.helpers.DefaultHandler#characters(char[], int, int)
*/
public
@Override
void characters(char[] ch, int start, int length) {
String chars = new String(ch, start, length);
mString = mString.concat(chars);
}
@Override
public void endElement(String uri, String localName, String name) {
if (localName.equals("points")) {
if (isPolyline) {
//detailed piece of route for the step, to add:
ArrayList<GeoPoint> polyLine = PolylineEncoder.decode(mString, 10);
mRoute.routeHigh.addAll(polyLine);
} else if (isOverviewPolyline) {
//low-def polyline for the whole route:
mRoute.setRouteLow(PolylineEncoder.decode(mString, 10));
}
} else if (localName.equals("polyline")) {
isPolyline = false;
} else if (localName.equals("overview_polyline")) {
isOverviewPolyline = false;
} else if (localName.equals("value")) {
mValue = Integer.parseInt(mString);
} else if (localName.equals("duration")) {
if (isStep)
mNode.duration = mValue;
else
mLeg.duration = mValue;
isDuration = false;
} else if (localName.equals("distance")) {
if (isStep)
mNode.length = mValue / 1000.0;
else
mLeg.length = mValue / 1000.0;
isDistance = false;
} else if (localName.equals("html_instructions")) {
if (isStep) {
mString = mString.replaceAll("<[^>]*>", " "); //remove everything in <...>
mString = mString.replaceAll("&nbsp;", " ");
mNode.instructions = mString;
//log.debug(mString);
}
} else if (localName.equals("start_location")) {
if (isStep)
mNode.location = new GeoPoint(mLat, mLng);
} else if (localName.equals("step")) {
mRoute.nodes.add(mNode);
isStep = false;
} else if (localName.equals("leg")) {
mRoute.legs.add(mLeg);
isLeg = false;
} else if (localName.equals("lat")) {
mLat = Double.parseDouble(mString);
} else if (localName.equals("lng")) {
mLng = Double.parseDouble(mString);
} else if (localName.equals("northeast")) {
if (isBB) {
mNorth = mLat;
mEast = mLng;
}
} else if (localName.equals("southwest")) {
if (isBB) {
mSouth = mLat;
mWest = mLng;
}
} else if (localName.equals("bounds")) {
mRoute.boundingBox = new BoundingBox(mNorth, mEast, mSouth, mWest);
isBB = false;
}
}
}

View File

@@ -0,0 +1,289 @@
package org.osmdroid.routing.provider;
import org.oscim.core.BoundingBox;
import org.oscim.core.GeoPoint;
import org.osmdroid.routing.Route;
import org.osmdroid.routing.RouteNode;
import org.osmdroid.routing.RouteProvider;
import org.osmdroid.utils.HttpConnection;
import org.osmdroid.utils.PolylineEncoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
/**
* class to get a route between a start and a destination point, going through a
* list of waypoints. It uses MapQuest open, public and free API, based on
* OpenStreetMap data. <br>
* See http://open.mapquestapi.com/guidance
*
* @author M.Kergall
*/
public class MapQuestRouteProvider extends RouteProvider {
final static Logger log = LoggerFactory.getLogger(MapQuestRouteProvider.class);
static final String MAPQUEST_GUIDANCE_SERVICE = "http://open.mapquestapi.com/guidance/v0/route?";
/**
* Build the URL to MapQuest service returning a route in XML format
*
* @param waypoints : array of waypoints, as [lat, lng], from start point to end
* point.
* @return ...
*/
protected String getUrl(List<GeoPoint> waypoints) {
StringBuffer urlString = new StringBuffer(MAPQUEST_GUIDANCE_SERVICE);
urlString.append("from=");
GeoPoint p = waypoints.get(0);
urlString.append(geoPointAsString(p));
for (int i = 1; i < waypoints.size(); i++) {
p = waypoints.get(i);
urlString.append("&to=" + geoPointAsString(p));
}
urlString.append("&outFormat=xml");
urlString.append("&shapeFormat=cmp"); // encoded polyline, much faster
urlString.append("&narrativeType=text"); // or "none"
// Locale locale = Locale.getDefault();
// urlString.append("&locale="+locale.getLanguage()+"_"+locale.getCountry());
urlString.append("&unit=k&fishbone=false");
// urlString.append("&generalizeAfter=500" /*+&generalize=2"*/);
// 500 points max, 2 meters tolerance
// Warning: MapQuest Open API doc is sometimes WRONG:
// - use unit, not units
// - use fishbone, not enableFishbone
// - locale (fr_FR, en_US) is supported but not documented.
// - generalize and generalizeAfter are not properly implemented
urlString.append(mOptions);
return urlString.toString();
}
/**
* @param waypoints : list of GeoPoints. Must have at least 2 entries, start and
* end points.
* @return the route
*/
@Override
public Route getRoute(List<GeoPoint> waypoints) {
String url = getUrl(waypoints);
log.debug("MapQuestRouteManager.getRoute:" + url);
Route route = null;
HttpConnection connection = new HttpConnection();
connection.doGet(url);
InputStream stream = connection.getStream();
if (stream != null)
route = getRouteXML(stream, waypoints);
if (route == null || route.routeHigh.size() == 0) {
// Create default route:
route = new Route(waypoints);
}
connection.close();
log.debug("MapQuestRouteManager.getRoute - finished");
return route;
}
/**
* XML implementation
*
* @param is : input stream to parse
* @param waypoints ...
* @return the route ...
*/
protected Route getRouteXML(InputStream is, List<GeoPoint> waypoints) {
XMLHandler handler = new XMLHandler();
try {
SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
parser.parse(is, handler);
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Route route = handler.mRoute;
if (route != null && route.routeHigh.size() > 0) {
route.nodes = finalizeNodes(route.nodes, handler.mLinks, route.routeHigh);
route.buildLegs(waypoints);
route.status = Route.STATUS_OK;
}
return route;
}
protected List<RouteNode> finalizeNodes(List<RouteNode> mNodes,
List<RouteLink> mLinks, List<GeoPoint> polyline) {
int n = mNodes.size();
if (n == 0)
return mNodes;
ArrayList<RouteNode> newNodes = new ArrayList<RouteNode>(n);
RouteNode lastNode = null;
for (int i = 1; i < n - 1; i++) { // 1, n-1 => first and last MapQuest
// nodes are irrelevant.
RouteNode node = mNodes.get(i);
RouteLink link = mLinks.get(node.nextRouteLink);
if (lastNode != null && (node.instructions == null || node.maneuverType == 0)) {
// this node is irrelevant, don't keep it,
// but update values of last node:
lastNode.length += link.mLength;
lastNode.duration += (node.duration + link.mDuration);
} else {
node.length = link.mLength;
node.duration += link.mDuration;
int locationIndex = link.mShapeIndex;
node.location = polyline.get(locationIndex);
newNodes.add(node);
lastNode = node;
}
}
// switch to the new array of nodes:
return newNodes;
}
}
/**
* Route Link is a portion of route between 2 "nodes" or intersections
*/
class RouteLink {
/**
* in km/h
*/
public double mSpeed;
/**
* in km
*/
public double mLength;
/**
* in sec
*/
public double mDuration;
/**
* starting point of the link, as index in initial polyline
*/
public int mShapeIndex;
}
/**
* XMLHandler: class to handle XML generated by MapQuest "guidance" open API.
*/
class XMLHandler extends DefaultHandler {
public Route mRoute;
public ArrayList<RouteLink> mLinks;
boolean isBB;
boolean isGuidanceNodeCollection;
private String mString;
double mLat, mLng;
double mNorth, mWest, mSouth, mEast;
RouteLink mLink;
RouteNode mNode;
public XMLHandler() {
isBB = isGuidanceNodeCollection = false;
mRoute = new Route();
mLinks = new ArrayList<RouteLink>();
}
@Override
public void startElement(String uri, String localName, String name,
Attributes attributes) {
if (localName.equals("boundingBox"))
isBB = true;
else if (localName.equals("link"))
mLink = new RouteLink();
else if (localName.equals("node"))
mNode = new RouteNode();
else if (localName.equals("GuidanceNodeCollection"))
isGuidanceNodeCollection = true;
mString = new String();
}
/**
* Overrides org.xml.sax.helpers.DefaultHandler#characters(char[], int, int)
*/
@Override
public void characters(char[] ch, int start, int length) {
String chars = new String(ch, start, length);
mString = mString.concat(chars);
}
@Override
public void endElement(String uri, String localName, String name) {
if (localName.equals("lat")) {
mLat = Double.parseDouble(mString);
} else if (localName.equals("lng")) {
mLng = Double.parseDouble(mString);
} else if (localName.equals("shapePoints")) {
mRoute.routeHigh = PolylineEncoder.decode(mString, 10);
// log.debug("High="+mRoute.mRouteHigh.size());
} else if (localName.equals("generalizedShape")) {
mRoute.setRouteLow(PolylineEncoder.decode(mString, 10));
// log.debug("Low="+mRoute.mRouteLow.size());
} else if (localName.equals("length")) {
mLink.mLength = Double.parseDouble(mString);
} else if (localName.equals("speed")) {
mLink.mSpeed = Double.parseDouble(mString);
} else if (localName.equals("shapeIndex")) {
mLink.mShapeIndex = Integer.parseInt(mString);
} else if (localName.equals("link")) {
// End of a link: update route attributes:
// GuidanceLinkCollection could in theory contain additional unused
// links,
// but normally not with fishbone set to false.
mLink.mDuration = mLink.mLength / mLink.mSpeed * 3600.0;
mLinks.add(mLink);
mRoute.length += mLink.mLength;
mRoute.duration += mLink.mDuration;
mLink = null;
} else if (localName.equals("turnCost")) {
int turnCost = Integer.parseInt(mString);
mNode.duration += turnCost;
mRoute.duration += turnCost;
} else if (localName.equals("maneuverType")) {
mNode.maneuverType = Integer.parseInt(mString);
} else if (localName.equals("info")) {
if (isGuidanceNodeCollection) {
if (mNode.instructions == null)
// this is first "info" value for this node, keep it:
mNode.instructions = mString;
}
} else if (localName.equals("linkId")) {
if (isGuidanceNodeCollection)
mNode.nextRouteLink = Integer.parseInt(mString);
} else if (localName.equals("node")) {
mRoute.nodes.add(mNode);
mNode = null;
} else if (localName.equals("GuidanceNodeCollection")) {
isGuidanceNodeCollection = false;
} else if (localName.equals("ul")) {
if (isBB) {
mNorth = mLat;
mWest = mLng;
}
} else if (localName.equals("lr")) {
if (isBB) {
mSouth = mLat;
mEast = mLng;
}
} else if (localName.equals("boundingBox")) {
mRoute.boundingBox = new BoundingBox(mNorth, mEast, mSouth, mWest);
isBB = false;
}
}
}

View File

@@ -0,0 +1,294 @@
package org.osmdroid.routing.provider;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.oscim.core.BoundingBox;
import org.oscim.core.GeoPoint;
import org.osmdroid.routing.Route;
import org.osmdroid.routing.RouteNode;
import org.osmdroid.routing.RouteProvider;
import org.osmdroid.utils.BonusPackHelper;
import org.osmdroid.utils.HttpConnection;
import org.osmdroid.utils.PolylineEncoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
/**
* get a route between a start and a destination point. It uses OSRM, a free
* open source routing service based on OpenSteetMap data. <br>
* See https://github.com/DennisOSRM/Project-OSRM/wiki/Server-api<br>
* It requests by default the OSRM demo site. Use setService() to request an
* other (for instance your own) OSRM service. <br>
* TODO: improve internationalization of instructions
*
* @author M.Kergall
*/
public class OSRMRouteProvider extends RouteProvider {
final static Logger log = LoggerFactory.getLogger(OSRMRouteProvider.class);
// 1 for 6 digit precision, 10 for 5
private final static int ENCODING_PRECISION = 1;
//static final String OSRM_SERVICE = "http://city.informatik.uni-bremen.de:5000/viaroute?";
//static final String OSRM_SERVICE = "http://city.informatik.uni-bremen.de:5001/viaroute?";
static final String OSRM_SERVICE = "http://router.project-osrm.org/viaroute?";
//Note that the result of OSRM is quite close to Cloudmade NavEngine format:
//http://developers.cloudmade.com/wiki/navengine/JSON_format
protected String mServiceUrl;
protected String mUserAgent;
/**
* mapping from OSRM directions to MapQuest maneuver IDs:
*/
static final HashMap<String, Integer> MANEUVERS;
static {
MANEUVERS = new HashMap<String, Integer>();
MANEUVERS.put("0", Integer.valueOf(0)); //No instruction
MANEUVERS.put("1", Integer.valueOf(1)); //Continue
MANEUVERS.put("2", Integer.valueOf(6)); //Slight right
MANEUVERS.put("3", Integer.valueOf(7)); //Right
MANEUVERS.put("4", Integer.valueOf(8)); //Sharp right
MANEUVERS.put("5", Integer.valueOf(12)); //U-turn
MANEUVERS.put("6", Integer.valueOf(5)); //Sharp left
MANEUVERS.put("7", Integer.valueOf(4)); //Left
MANEUVERS.put("8", Integer.valueOf(3)); //Slight left
MANEUVERS.put("9", Integer.valueOf(24)); //Arrived (at waypoint)
//MANEUVERS.put("10", Integer.valueOf(0)); //"Head" => used by OSRM as the start node
MANEUVERS.put("11-1", Integer.valueOf(27)); //Round-about, 1st exit
MANEUVERS.put("11-2", Integer.valueOf(28)); //2nd exit, etc ...
MANEUVERS.put("11-3", Integer.valueOf(29));
MANEUVERS.put("11-4", Integer.valueOf(30));
MANEUVERS.put("11-5", Integer.valueOf(31));
MANEUVERS.put("11-6", Integer.valueOf(32));
MANEUVERS.put("11-7", Integer.valueOf(33));
MANEUVERS.put("11-8", Integer.valueOf(34)); //Round-about, 8th exit
MANEUVERS.put("15", Integer.valueOf(24)); //Arrived
}
//From: Project-OSRM-Web / WebContent / localization / OSRM.Locale.en.js
// driving directions
// %s: route name
// %d: direction => removed
// <*>: will only be printed when there actually is a route name
static final HashMap<String, HashMap<String, String>> DIRECTIONS;
static {
DIRECTIONS = new HashMap<String, HashMap<String, String>>();
HashMap<String, String> directions;
directions = new HashMap<String, String>();
DIRECTIONS.put("en", directions);
directions.put("0", "Unknown instruction< on %s>");
directions.put("1", "Continue< on %s>");
directions.put("2", "Turn slight right< on %s>");
directions.put("3", "Turn right< on %s>");
directions.put("4", "Turn sharp right< on %s>");
directions.put("5", "U-Turn< on %s>");
directions.put("6", "Turn sharp left< on %s>");
directions.put("7", "Turn left< on %s>");
directions.put("8", "Turn slight left< on %s>");
directions.put("9", "You have reached a waypoint of your trip");
directions.put("10", "<Go on %s>");
directions.put("11-1", "Enter roundabout and leave at first exit< on %s>");
directions.put("11-2", "Enter roundabout and leave at second exit< on %s>");
directions.put("11-3", "Enter roundabout and leave at third exit< on %s>");
directions.put("11-4", "Enter roundabout and leave at fourth exit< on %s>");
directions.put("11-5", "Enter roundabout and leave at fifth exit< on %s>");
directions.put("11-6", "Enter roundabout and leave at sixth exit< on %s>");
directions.put("11-7", "Enter roundabout and leave at seventh exit< on %s>");
directions.put("11-8", "Enter roundabout and leave at eighth exit< on %s>");
directions.put("11-9", "Enter roundabout and leave at nineth exit< on %s>");
directions.put("15", "You have reached your destination");
directions = new HashMap<String, String>();
DIRECTIONS.put("fr", directions);
directions.put("0", "Instruction inconnue< sur %s>");
directions.put("1", "Continuez< sur %s>");
directions.put("2", "Tournez légèrement à droite< sur %s>");
directions.put("3", "Tournez à droite< sur %s>");
directions.put("4", "Tournez fortement à droite< sur %s>");
directions.put("5", "Faites demi-tour< sur %s>");
directions.put("6", "Tournez fortement à gauche< sur %s>");
directions.put("7", "Tournez à gauche< sur %s>");
directions.put("8", "Tournez légèrement à gauche< sur %s>");
directions.put("9", "Vous êtes arrivé à une étape de votre voyage");
directions.put("10", "<Prenez %s>");
directions.put("11-1", "Au rond-point, prenez la première sortie< sur %s>");
directions.put("11-2", "Au rond-point, prenez la deuxième sortie< sur %s>");
directions.put("11-3", "Au rond-point, prenez la troisième sortie< sur %s>");
directions.put("11-4", "Au rond-point, prenez la quatrième sortie< sur %s>");
directions.put("11-5", "Au rond-point, prenez la cinquième sortie< sur %s>");
directions.put("11-6", "Au rond-point, prenez la sixième sortie< sur %s>");
directions.put("11-7", "Au rond-point, prenez la septième sortie< sur %s>");
directions.put("11-8", "Au rond-point, prenez la huitième sortie< sur %s>");
directions.put("11-9", "Au rond-point, prenez la neuvième sortie< sur %s>");
directions.put("15", "Vous êtes arrivé");
directions = new HashMap<String, String>();
DIRECTIONS.put("pl", directions);
directions.put("0", "Nieznana instrukcja<w %s>");
directions.put("1", "Kontynuuj jazdę<na %s>");
directions.put("2", "Skręć lekko w prawo<w %s>");
directions.put("3", "Skręć w prawo<w %s>");
directions.put("4", "Skręć ostro w prawo<w %s>");
directions.put("5", "Zawróć<na %s>");
directions.put("6", "Skręć ostro w lewo<w %s>");
directions.put("7", "Skręć w lewo<w %s>");
directions.put("8", "Skręć lekko w lewo<w %s>");
directions.put("9", "Dotarłeś do punktu pośredniego");
directions.put("10", "<Jedź %s>");
directions.put("11-1", "Wjedź na rondo i opuść je pierwszym zjazdem<w %s>");
directions.put("11-2", "Wjedź na rondo i opuść je drugim zjazdem<w %s>");
directions.put("11-3", "Wjedź na rondo i opuść je trzecim zjazdem<w %s>");
directions.put("11-4", "Wjedź na rondo i opuść je czwartym zjazdem<w %s>");
directions.put("11-5", "Wjedź na rondo i opuść je piątym zjazdem<w %s>");
directions.put("11-6", "Wjedź na rondo i opuść je szóstym zjazdem<w %s>");
directions.put("11-7", "Wjedź na rondo i opuść je siódmym zjazdem<w %s>");
directions.put("11-8", "Wjedź na rondo i opuść je ósmym zjazdem<w %s>");
directions.put("11-9", "Wjedź na rondo i opuść je dziewiątym zjazdem<w %s>");
directions.put("15", "Dotarłeś do celu podróży");
}
public OSRMRouteProvider() {
super();
mServiceUrl = OSRM_SERVICE;
mUserAgent = BonusPackHelper.DEFAULT_USER_AGENT; //set user agent to the default one.
}
/**
* allows to request on an other site than OSRM demo site
*
* @param serviceUrl ...
*/
public void setService(String serviceUrl) {
mServiceUrl = serviceUrl;
}
/**
* allows to send to OSRM service a user agent specific to the app, instead
* of the default user agent of OSMBonusPack lib.
*
* @param userAgent ...
*/
public void setUserAgent(String userAgent) {
mUserAgent = userAgent;
}
protected String getUrl(List<GeoPoint> waypoints) {
StringBuffer urlString = new StringBuffer(mServiceUrl);
for (int i = 0; i < waypoints.size(); i++) {
GeoPoint p = waypoints.get(i);
urlString.append("&loc=" + geoPointAsString(p));
}
urlString.append(mOptions);
return urlString.toString();
}
@Override
public Route getRoute(List<GeoPoint> waypoints) {
String url = getUrl(waypoints);
log.debug("OSRMRouteManager.getRoute:" + url);
//String jString = BonusPackHelper.requestStringFromUrl(url);
HttpConnection connection = new HttpConnection();
connection.setUserAgent(mUserAgent);
connection.doGet(url);
String jString = connection.getContentAsString();
connection.close();
if (jString == null) {
log.error("OSRMRouteManager::getRoute: request failed.");
return new Route(waypoints);
}
Locale l = Locale.getDefault();
HashMap<String, String> directions = DIRECTIONS.get(l.getLanguage());
if (directions == null)
directions = DIRECTIONS.get("en");
Route route = new Route();
try {
JSONObject jObject = new JSONObject(jString);
String route_geometry = jObject.getString("route_geometry");
route.routeHigh = PolylineEncoder.decode(route_geometry, ENCODING_PRECISION);
JSONArray jInstructions = jObject.getJSONArray("route_instructions");
int n = jInstructions.length();
RouteNode lastNode = null;
for (int i = 0; i < n; i++) {
JSONArray jInstruction = jInstructions.getJSONArray(i);
RouteNode node = new RouteNode();
int positionIndex = jInstruction.getInt(3);
node.location = route.routeHigh.get(positionIndex);
node.length = jInstruction.getInt(2) / 1000.0;
node.duration = jInstruction.getInt(4); //Segment duration in seconds.
String direction = jInstruction.getString(0);
String routeName = jInstruction.getString(1);
if (lastNode != null && "1".equals(direction) && "".equals(routeName)) {
//node "Continue" with no route name is useless, don't add it
lastNode.length += node.length;
lastNode.duration += node.duration;
} else {
node.maneuverType = getManeuverCode(direction);
node.instructions = buildInstructions(direction, routeName, directions);
//log.debug(direction+"=>"+node.mManeuverType+"; "+node.mInstructions);
route.nodes.add(node);
lastNode = node;
}
}
JSONObject jSummary = jObject.getJSONObject("route_summary");
route.length = jSummary.getInt("total_distance") / 1000.0;
route.duration = jSummary.getInt("total_time");
} catch (JSONException e) {
e.printStackTrace();
return new Route(waypoints);
}
if (route.routeHigh.size() == 0) {
//Create default route:
route = new Route(waypoints);
} else {
route.buildLegs(waypoints);
BoundingBox bb = BoundingBox.fromGeoPoints(route.routeHigh);
//Correcting osmdroid bug #359:
route.boundingBox = bb;
// new BoundingBox(
// bb.getLatSouthE6(), bb.getLonWestE6(), bb.getLatNorthE6(), bb.getLonEastE6());
route.status = Route.STATUS_OK;
}
log.debug("OSRMRouteManager.getRoute - finished");
return route;
}
protected int getManeuverCode(String direction) {
Integer code = MANEUVERS.get(direction);
if (code != null)
return code.intValue();
return 0;
}
protected String buildInstructions(String direction, String routeName,
HashMap<String, String> directions) {
if (directions == null)
return null;
direction = directions.get(direction);
if (direction == null)
return null;
String instructions = null;
if (routeName.equals(""))
//remove "<*>"
instructions = direction.replaceFirst("<[^>]*>", "");
else {
direction = direction.replace('<', ' ');
direction = direction.replace('>', ' ');
instructions = String.format(direction, routeName);
}
return instructions;
}
}

View File

@@ -0,0 +1,112 @@
package org.osmdroid.utils;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import java.io.FileNotFoundException;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
/**
* Useful functions and common constants.
*
* @author M.Kergall
*/
public class BonusPackHelper {
/**
* Log tag.
*/
public static final String LOG_TAG = "BONUSPACK";
/**
* User agent sent to services by default
*/
public static final String DEFAULT_USER_AGENT = "OsmBonusPack/1";
/**
* @return true if the device is the emulator, false if actual device.
*/
public static boolean isEmulator() {
//return Build.MANUFACTURER.equals("unknown");
return ("google_sdk".equals(Build.PRODUCT) || "sdk".equals(Build.PRODUCT));
}
/**
* @param connection ...
* @return the whole content of the http request, as a string
*/
private static String readStream(HttpConnection connection) {
String result = connection.getContentAsString();
return result;
}
/**
* sends an http request, and returns the whole content result in a String.
*
* @param url ...
* @return the whole content, or null if any issue.
*/
public static String requestStringFromUrl(String url) {
HttpConnection connection = new HttpConnection();
connection.doGet(url);
String result = readStream(connection);
connection.close();
return result;
}
/**
* Loads a bitmap from a url.
*
* @param url ...
* @return the bitmap, or null if any issue.
*/
public static Bitmap loadBitmap(String url) {
Bitmap bitmap = null;
try {
InputStream is = (InputStream) new URL(url).getContent();
bitmap = BitmapFactory.decodeStream(new FlushedInputStream(is));
//Alternative providing better handling on loading errors?
/* Drawable d = Drawable.createFromStream(new
* FlushedInputStream(is), null); if (is != null) is.close(); if (d
* != null) bitmap = ((BitmapDrawable)d).getBitmap(); */
} catch (FileNotFoundException e) {
//log.debug("image not available: " + url);
} catch (Exception e) {
e.printStackTrace();
return null;
}
return bitmap;
}
/**
* Workaround on Android issue see
* http://stackoverflow.com/questions/4601352
* /createfromstream-in-android-returning-null-for-certain-url
*/
static class FlushedInputStream extends FilterInputStream {
public FlushedInputStream(InputStream inputStream) {
super(inputStream);
}
@Override
public long skip(long n) throws IOException {
long totalBytesSkipped = 0L;
while (totalBytesSkipped < n) {
long bytesSkipped = in.skip(n - totalBytesSkipped);
if (bytesSkipped == 0L) {
int byteValue = read();
if (byteValue < 0)
break; // we reached EOF
bytesSkipped = 1; // we read one byte
}
totalBytesSkipped += bytesSkipped;
}
return totalBytesSkipped;
}
}
}

View File

@@ -0,0 +1,141 @@
package org.osmdroid.utils;
import org.oscim.core.GeoPoint;
import java.util.ArrayList;
import java.util.List;
/**
* Reduces the number of points in a shape using the Douglas-Peucker algorithm. <br>
* From:
* http://www.phpriot.com/articles/reducing-map-path-douglas-peucker-algorithm/4<br>
* Ported from PHP to Java. "marked" array added to optimize.
*
* @author M.Kergall
*/
public class DouglasPeuckerReducer {
/**
* Reduce the number of points in a shape using the Douglas-Peucker
* algorithm
*
* @param shape The shape to reduce
* @param tolerance The tolerance to decide whether or not to keep a point, in the
* coordinate system of the points (micro-degrees here)
* @return the reduced shape
*/
public static List<GeoPoint> reduceWithTolerance(List<GeoPoint> shape,
double tolerance) {
int n = shape.size();
// if a shape has 2 or less points it cannot be reduced
if (tolerance <= 0 || n < 3) {
return shape;
}
boolean[] marked = new boolean[n]; //vertex indexes to keep will be marked as "true"
for (int i = 1; i < n - 1; i++)
marked[i] = false;
// automatically add the first and last point to the returned shape
marked[0] = marked[n - 1] = true;
// the first and last points in the original shape are
// used as the entry point to the algorithm.
douglasPeuckerReduction(
shape, // original shape
marked, // reduced shape
tolerance, // tolerance
0, // index of first point
n - 1 // index of last point
);
// all done, return the reduced shape
ArrayList<GeoPoint> newShape = new ArrayList<GeoPoint>(n); // the new shape to return
for (int i = 0; i < n; i++) {
if (marked[i])
newShape.add(shape.get(i));
}
return newShape;
}
/**
* Reduce the points in shape between the specified first and last index.
* Mark the points to keep in marked[]
*
* @param shape The original shape
* @param marked The points to keep (marked as true)
* @param tolerance The tolerance to determine if a point is kept
* @param firstIdx The index in original shape's point of the starting point for
* this line segment
* @param lastIdx The index in original shape's point of the ending point for
* this line segment
*/
private static void douglasPeuckerReduction(List<GeoPoint> shape, boolean[] marked,
double tolerance, int firstIdx, int lastIdx) {
if (lastIdx <= firstIdx + 1) {
// overlapping indexes, just return
return;
}
// loop over the points between the first and last points
// and find the point that is the farthest away
double maxDistance = 0.0;
int indexFarthest = 0;
GeoPoint firstPoint = shape.get(firstIdx);
GeoPoint lastPoint = shape.get(lastIdx);
for (int idx = firstIdx + 1; idx < lastIdx; idx++) {
GeoPoint point = shape.get(idx);
double distance = orthogonalDistance(point, firstPoint, lastPoint);
// keep the point with the greatest distance
if (distance > maxDistance) {
maxDistance = distance;
indexFarthest = idx;
}
}
if (maxDistance > tolerance) {
//The farthest point is outside the tolerance: it is marked and the algorithm continues.
marked[indexFarthest] = true;
// reduce the shape between the starting point to newly found point
douglasPeuckerReduction(shape, marked, tolerance, firstIdx, indexFarthest);
// reduce the shape between the newly found point and the finishing point
douglasPeuckerReduction(shape, marked, tolerance, indexFarthest, lastIdx);
}
//else: the farthest point is within the tolerance, the whole segment is discarded.
}
/**
* Calculate the orthogonal distance from the line joining the lineStart and
* lineEnd points to point
*
* @param point The point the distance is being calculated for
* @param lineStart The point that starts the line
* @param lineEnd The point that ends the line
* @return The distance in points coordinate system
*/
public static double orthogonalDistance(GeoPoint point, GeoPoint lineStart, GeoPoint lineEnd) {
double area = Math.abs(
(
1.0 * lineStart.latitudeE6 * lineEnd.longitudeE6
+ 1.0 * lineEnd.latitudeE6 * point.longitudeE6
+ 1.0 * point.latitudeE6 * lineStart.longitudeE6
- 1.0 * lineEnd.latitudeE6 * lineStart.longitudeE6
- 1.0 * point.latitudeE6 * lineEnd.longitudeE6
- 1.0 * lineStart.latitudeE6 * point.longitudeE6
) / 2.0
);
double bottom = Math.hypot(
lineStart.latitudeE6 - lineEnd.latitudeE6,
lineStart.longitudeE6 - lineEnd.longitudeE6
);
return (area / bottom * 2.0);
}
}

View File

@@ -0,0 +1,119 @@
package org.osmdroid.utils;
import android.util.Log;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.TimeUnit;
/**
* A "very very simple to use" class for performing http get and post requests.
* So many ways to do that, and potential subtle issues.
* If complexity should be added to handle even more issues, complexity should be put here and only here.
* <p/>
* Typical usage:
* <pre>HttpConnection connection = new HttpConnection();
* connection.doGet("http://www.google.com");
* InputStream stream = connection.getStream();
* if (stream != null) {
* //use this stream, for buffer reading, or XML SAX parsing, or whatever...
* }
* connection.close();</pre>
*/
public class HttpConnection {
private final static int TIMEOUT_CONNECTION = 3000; //ms
private final static int TIMEOUT_SOCKET = 10000; //ms
private static OkHttpClient client;
private InputStream stream;
private String mUserAgent;
private Response response;
private static OkHttpClient getOkHttpClient() {
if (client == null) {
client = new OkHttpClient();
client.setConnectTimeout(TIMEOUT_CONNECTION, TimeUnit.MILLISECONDS);
client.setReadTimeout(TIMEOUT_SOCKET, TimeUnit.MILLISECONDS);
}
return client;
}
public HttpConnection() {
/*
client = new OkHttpClient();
client.setConnectTimeout(TIMEOUT_CONNECTION, TimeUnit.MILLISECONDS);
client.setReadTimeout(TIMEOUT_SOCKET, TimeUnit.MILLISECONDS);
*/
}
public void setUserAgent(String userAgent) {
mUserAgent = userAgent;
}
public void doGet(final String url) {
try {
Request.Builder request = new Request.Builder().url(url);
if (mUserAgent != null)
request.addHeader("User-Agent", mUserAgent);
response = getOkHttpClient().newCall(request.build()).execute();
Integer status = response.code();
if (status != 200) {
Log.e(BonusPackHelper.LOG_TAG, "Invalid response from server: " + status.toString());
}
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* @return the opened InputStream, or null if creation failed for any reason.
*/
public InputStream getStream() {
try {
if (response == null)
return null;
stream = response.body().byteStream();
return stream;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
/**
* @return the whole content as a String, or null if creation failed for any reason.
*/
public String getContentAsString() {
try {
if (response == null)
return null;
return response.body().string();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
/**
* Calling close once is mandatory.
*/
public void close() {
if (stream != null) {
try {
stream.close();
stream = null;
} catch (IOException e) {
e.printStackTrace();
}
}
/*
if (client != null)
client = null;
*/
}
}

View File

@@ -0,0 +1,22 @@
/*
* Copyright 2010, 2011, 2012 mapsforge.org
*
* This program is free software: you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.osmdroid.utils;
public class MathConstants {
public static final double PI180E6 = (Math.PI / 180) / 1000000.0;
public static final double PIx4 = Math.PI * 4;
}

View File

@@ -0,0 +1,94 @@
package org.osmdroid.utils;
import org.oscim.core.GeoPoint;
import java.util.ArrayList;
/**
* Methods to encode and decode a polyline with Google polyline
* encoding/decoding scheme. See
* https://developers.google.com/maps/documentation/utilities/polylinealgorithm
*/
public class PolylineEncoder {
private static StringBuffer encodeSignedNumber(int num) {
int sgn_num = num << 1;
if (num < 0) {
sgn_num = ~(sgn_num);
}
return (encodeNumber(sgn_num));
}
private static StringBuffer encodeNumber(int num) {
StringBuffer encodeString = new StringBuffer();
while (num >= 0x20) {
int nextValue = (0x20 | (num & 0x1f)) + 63;
encodeString.append((char) (nextValue));
num >>= 5;
}
num += 63;
encodeString.append((char) (num));
return encodeString;
}
/**
* Encode a polyline with Google polyline encoding method
*
* @param polyline the polyline
* @param precision 1 for a 6 digits encoding, 10 for a 5 digits encoding.
* @return the encoded polyline, as a String
*/
public static String encode(ArrayList<GeoPoint> polyline, int precision) {
StringBuffer encodedPoints = new StringBuffer();
int prev_lat = 0, prev_lng = 0;
for (GeoPoint trackpoint : polyline) {
int lat = trackpoint.latitudeE6 / precision;
int lng = trackpoint.longitudeE6 / precision;
encodedPoints.append(encodeSignedNumber(lat - prev_lat));
encodedPoints.append(encodeSignedNumber(lng - prev_lng));
prev_lat = lat;
prev_lng = lng;
}
return encodedPoints.toString();
}
/**
* Decode a "Google-encoded" polyline
*
* @param encodedString ...
* @param precision 1 for a 6 digits encoding, 10 for a 5 digits encoding.
* @return the polyline.
*/
public static ArrayList<GeoPoint> decode(String encodedString, int precision) {
ArrayList<GeoPoint> polyline = new ArrayList<GeoPoint>();
int index = 0;
int len = encodedString.length();
int lat = 0, lng = 0;
while (index < len) {
int b, shift = 0, result = 0;
do {
b = encodedString.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lat += dlat;
shift = 0;
result = 0;
do {
b = encodedString.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lng += dlng;
GeoPoint p = new GeoPoint(lat * precision, lng * precision);
polyline.add(p);
}
return polyline;
}
}