();
- options.put("mapfile", file.getAbsolutePath());
+ MapOptions options = new MapOptions(MapDatabases.MAP_READER);
+ options.put("file", file.getAbsolutePath());
this.openResult = mapDatabase.open(options);
diff --git a/VectorTileMap/src/org/oscim/app/filefilter/ValidRenderTheme.java b/TileMapApp/src/org/oscim/app/filefilter/ValidRenderTheme.java
similarity index 100%
rename from VectorTileMap/src/org/oscim/app/filefilter/ValidRenderTheme.java
rename to TileMapApp/src/org/oscim/app/filefilter/ValidRenderTheme.java
diff --git a/VectorTileMap/src/org/oscim/app/filepicker/FilePicker.java b/TileMapApp/src/org/oscim/app/filepicker/FilePicker.java
similarity index 83%
rename from VectorTileMap/src/org/oscim/app/filepicker/FilePicker.java
rename to TileMapApp/src/org/oscim/app/filepicker/FilePicker.java
index 6470662..2f7400e 100755
--- a/VectorTileMap/src/org/oscim/app/filepicker/FilePicker.java
+++ b/TileMapApp/src/org/oscim/app/filepicker/FilePicker.java
@@ -36,16 +36,22 @@
import android.widget.GridView;
/**
- * A FilePicker displays the contents of directories. The user can navigate within the file system and select a single
- * file whose path is then returned to the calling activity. The ordering of directory contents can be specified via
- * {@link #setFileComparator(Comparator)}. By default subfolders and files are grouped and each group is ordered
+ * A FilePicker displays the contents of directories. The user can navigate
+ * within the file system and select a single
+ * file whose path is then returned to the calling activity. The ordering of
+ * directory contents can be specified via
+ * {@link #setFileComparator(Comparator)}. By default subfolders and files are
+ * grouped and each group is ordered
* alphabetically.
*
- * A {@link FileFilter} can be activated via {@link #setFileDisplayFilter(FileFilter)} to restrict the displayed files
- * and folders. By default all files and folders are visible.
+ * A {@link FileFilter} can be activated via
+ * {@link #setFileDisplayFilter(FileFilter)} to restrict the displayed files and
+ * folders. By default all files and folders are visible.
*
- * Another FileFilter can be applied via {@link #setFileSelectFilter(ValidFileFilter)} to check if a
- * selected file is valid before its path is returned. By default all files are considered as valid and can be selected.
+ * Another FileFilter can be applied via
+ * {@link #setFileSelectFilter(ValidFileFilter)} to check if a selected file is
+ * valid before its path is returned. By default all files are considered as
+ * valid and can be selected.
*/
public class FilePicker extends Activity implements AdapterView.OnItemClickListener {
/**
@@ -63,9 +69,9 @@ public class FilePicker extends Activity implements AdapterView.OnItemClickListe
private static final String PREFERENCES_FILE = "FilePicker";
/**
- * Sets the file comparator which is used to order the contents of all directories before displaying them. If set to
+ * Sets the file comparator which is used to order the contents of all
+ * directories before displaying them. If set to
* null, subfolders and files will not be ordered.
- *
* @param fileComparator
* the file comparator (may be null).
*/
@@ -74,9 +80,9 @@ public static void setFileComparator(Comparator fileComparator) {
}
/**
- * Sets the file display filter. This filter is used to determine which files and subfolders of directories will be
+ * Sets the file display filter. This filter is used to determine which
+ * files and subfolders of directories will be
* displayed. If set to null, all files and subfolders are shown.
- *
* @param fileDisplayFilter
* the file display filter (may be null).
*/
@@ -85,9 +91,9 @@ public static void setFileDisplayFilter(FileFilter fileDisplayFilter) {
}
/**
- * Sets the file select filter. This filter is used when the user selects a file to determine if it is valid. If set
+ * Sets the file select filter. This filter is used when the user selects a
+ * file to determine if it is valid. If set
* to null, all files are considered as valid.
- *
* @param fileSelectFilter
* the file selection filter (may be null).
*/
@@ -97,7 +103,6 @@ public static void setFileSelectFilter(ValidFileFilter fileSelectFilter) {
/**
* Creates the default file comparator.
- *
* @return the default file comparator.
*/
private static Comparator getDefaultFileComparator() {
@@ -121,6 +126,7 @@ public int compare(File file1, File file2) {
private File[] files;
private File[] filesWithParentFolder;
+ @SuppressWarnings("deprecation")
@Override
public void onItemClick(AdapterView> parent, View view, int position, long id) {
File selectedFile = this.files[(int) id];
@@ -190,26 +196,26 @@ protected void onCreate(Bundle savedInstanceState) {
protected Dialog onCreateDialog(int id) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
switch (id) {
- case DIALOG_FILE_INVALID:
- builder.setIcon(android.R.drawable.ic_menu_info_details);
- builder.setTitle(R.string.error);
-
- StringBuilder stringBuilder = new StringBuilder();
- stringBuilder.append(getString(R.string.file_invalid));
- stringBuilder.append("\n\n");
- stringBuilder.append(FilePicker.fileSelectFilter.getFileOpenResult()
- .getErrorMessage());
-
- builder.setMessage(stringBuilder.toString());
- builder.setPositiveButton(R.string.ok, null);
- return builder.create();
- // case DIALOG_FILE_SELECT:
- // builder.setMessage(R.string.file_select);
- // builder.setPositiveButton(R.string.ok, null);
- // return builder.create();
- default:
- // do dialog will be created
- return null;
+ case DIALOG_FILE_INVALID:
+ builder.setIcon(android.R.drawable.ic_menu_info_details);
+ builder.setTitle(R.string.error);
+
+ StringBuilder stringBuilder = new StringBuilder();
+ stringBuilder.append(getString(R.string.file_invalid));
+ stringBuilder.append("\n\n");
+ stringBuilder.append(FilePicker.fileSelectFilter.getFileOpenResult()
+ .getErrorMessage());
+
+ builder.setMessage(stringBuilder.toString());
+ builder.setPositiveButton(R.string.ok, null);
+ return builder.create();
+ // case DIALOG_FILE_SELECT:
+ // builder.setMessage(R.string.file_select);
+ // builder.setPositiveButton(R.string.ok, null);
+ // return builder.create();
+ default:
+ // do dialog will be created
+ return null;
}
}
diff --git a/VectorTileMap/src/org/oscim/app/filepicker/FilePickerIconAdapter.java b/TileMapApp/src/org/oscim/app/filepicker/FilePickerIconAdapter.java
similarity index 97%
rename from VectorTileMap/src/org/oscim/app/filepicker/FilePickerIconAdapter.java
rename to TileMapApp/src/org/oscim/app/filepicker/FilePickerIconAdapter.java
index 11450a0..3e291c6 100755
--- a/VectorTileMap/src/org/oscim/app/filepicker/FilePickerIconAdapter.java
+++ b/TileMapApp/src/org/oscim/app/filepicker/FilePickerIconAdapter.java
@@ -37,9 +37,9 @@ class FilePickerIconAdapter extends BaseAdapter {
/**
* Creates a new FilePickerIconAdapter with the given context.
- *
* @param context
- * the context of this adapter, through which new Views are created.
+ * the context of this adapter, through which new Views are
+ * created.
*/
FilePickerIconAdapter(Context context) {
super();
@@ -98,11 +98,11 @@ public View getView(int index, View convertView, ViewGroup parent) {
/**
* Sets the data of this adapter.
- *
* @param files
* the new files for this adapter.
* @param newHasParentFolder
- * true if the file array has a parent folder at index 0, false otherwise.
+ * true if the file array has a parent folder at index 0, false
+ * otherwise.
*/
void setFiles(File[] files, boolean newHasParentFolder) {
this.files = files.clone();
diff --git a/VectorTileMap/src/org/oscim/app/preferences/EditPreferences.java b/TileMapApp/src/org/oscim/app/preferences/EditPreferences.java
similarity index 98%
rename from VectorTileMap/src/org/oscim/app/preferences/EditPreferences.java
rename to TileMapApp/src/org/oscim/app/preferences/EditPreferences.java
index 85da0f8..9df8927 100644
--- a/VectorTileMap/src/org/oscim/app/preferences/EditPreferences.java
+++ b/TileMapApp/src/org/oscim/app/preferences/EditPreferences.java
@@ -23,6 +23,7 @@
* Activity to edit the application preferences.
*/
public class EditPreferences extends PreferenceActivity {
+ @SuppressWarnings("deprecation")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
diff --git a/VectorTileMap/src/org/oscim/app/preferences/SeekBarPreference.java b/TileMapApp/src/org/oscim/app/preferences/SeekBarPreference.java
similarity index 100%
rename from VectorTileMap/src/org/oscim/app/preferences/SeekBarPreference.java
rename to TileMapApp/src/org/oscim/app/preferences/SeekBarPreference.java
diff --git a/VectorTileMap/src/org/osmdroid/location/FlickrPOIProvider.java b/TileMapApp/src/org/osmdroid/location/FlickrPOIProvider.java
similarity index 72%
rename from VectorTileMap/src/org/osmdroid/location/FlickrPOIProvider.java
rename to TileMapApp/src/org/osmdroid/location/FlickrPOIProvider.java
index 7917d12..bf74e41 100644
--- a/VectorTileMap/src/org/osmdroid/location/FlickrPOIProvider.java
+++ b/TileMapApp/src/org/osmdroid/location/FlickrPOIProvider.java
@@ -1,135 +1,165 @@
-package org.osmdroid.location;
-
-import java.util.ArrayList;
-
-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 android.util.Log;
-
-/**
- * POI Provider using Flickr service to get geolocalized photos.
- * @see "http://www.flickr.com/services/api/flickr.photos.search.html"
- * @author M.Kergall
- */
-public class FlickrPOIProvider {
-
- protected String mApiKey;
-
- /**
- * @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.d(BonusPackHelper.LOG_TAG,
- * "getPhoto:"+url); String jString =
- * BonusPackHelper.requestStringFromUrl(url); if (jString == null) {
- * Log.e(BonusPackHelper.LOG_TAG, "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 getThem(String fullUrl) {
- // for local debug: fullUrl = "http://10.0.2.2/flickr_mockup.json";
- Log.d(BonusPackHelper.LOG_TAG, "FlickrPOIProvider:get:" + fullUrl);
- String jString = BonusPackHelper.requestStringFromUrl(fullUrl);
- if (jString == null) {
- Log.e(BonusPackHelper.LOG_TAG, "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 pois = new ArrayList(n);
- for (int i = 0; i < n; i++) {
- JSONObject jPhoto = jPhotoArray.getJSONObject(i);
- String photoId = jPhoto.getString("id");
- POI poi = new POI(POI.POI_SERVICE_FLICKR);
- poi.location = new GeoPoint(
- jPhoto.getDouble("latitude"),
- jPhoto.getDouble("longitude"));
- poi.id = Long.parseLong(photoId);
- poi.type = jPhoto.getString("title");
- poi.thumbnailPath = jPhoto.getString("url_sq");
- String owner = jPhoto.getString("owner");
- poi.url = "http://www.flickr.com/photos/" + owner + "/" + photoId;
- pois.add(poi);
- }
- int total = jPhotos.getInt("total");
- Log.d(BonusPackHelper.LOG_TAG, "done:" + n + " got, 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 getPOIInside(BoundingBox boundingBox, int maxResults) {
- String url = getUrlInside(boundingBox, maxResults);
- return getThem(url);
- }
-
-}
+package org.osmdroid.location;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+
+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 android.util.Log;
+
+/**
+ * POI Provider using Flickr service to get geolocalized photos.
+ * @see "http://www.flickr.com/services/api/flickr.photos.search.html"
+ * @author M.Kergall
+ */
+public class FlickrPOIProvider implements POIProvider {
+
+ 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.d(BonusPackHelper.LOG_TAG,
+ * "getPhoto:"+url); String jString =
+ * BonusPackHelper.requestStringFromUrl(url); if (jString == null)
+ * {
+ * Log.e(BonusPackHelper.LOG_TAG,
+ * "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 getThem(String fullUrl) {
+ // for local debug: fullUrl = "http://10.0.2.2/flickr_mockup.json";
+ Log.d(BonusPackHelper.LOG_TAG, "FlickrPOIProvider:get:" + fullUrl);
+ String jString = BonusPackHelper.requestStringFromUrl(fullUrl);
+ if (jString == null) {
+ Log.e(BonusPackHelper.LOG_TAG, "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 pois = new ArrayList(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.d(BonusPackHelper.LOG_TAG, "done:" + n + " got, 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 getPOIInside(BoundingBox boundingBox, String query, int maxResults) {
+ String url = getUrlInside(boundingBox, maxResults);
+ return getThem(url);
+ }
+
+ HashMap mPrevious;
+
+ public void setPrevious(HashMap previous) {
+ mPrevious = previous;
+ }
+
+}
diff --git a/TileMapApp/src/org/osmdroid/location/FourSquareProvider.java b/TileMapApp/src/org/osmdroid/location/FourSquareProvider.java
new file mode 100644
index 0000000..3c56b93
--- /dev/null
+++ b/TileMapApp/src/org/osmdroid/location/FourSquareProvider.java
@@ -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 .
+ */
+package org.osmdroid.location;
+
+import java.io.IOException;
+import java.net.HttpURLConnection;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.net.URLEncoder;
+import java.util.ArrayList;
+
+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 android.content.Context;
+import android.content.Intent;
+import android.net.Uri;
+import android.os.AsyncTask;
+import android.util.Log;
+
+public class FourSquareProvider {
+
+ // 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 mIcons =
+ // (HashMap)Collections.synchronizedMap(new HashMap());
+
+ /**
+ * @param apiKey
+ * 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
+ 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 getThem(String fullUrl) {
+ // for local debug: fullUrl = "http://10.0.2.2/flickr_mockup.json";
+ Log.d(BonusPackHelper.LOG_TAG, "FlickrPOIProvider:get:" + fullUrl);
+ String jString = BonusPackHelper.requestStringFromUrl(fullUrl);
+ if (jString == null) {
+ Log.e(BonusPackHelper.LOG_TAG, "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 pois = new ArrayList(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 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() {
+
+ @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.d(BonusPackHelper.LOG_TAG, 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);
+
+ }
+}
diff --git a/VectorTileMap/src/org/osmdroid/location/GeoNamesPOIProvider.java b/TileMapApp/src/org/osmdroid/location/GeoNamesPOIProvider.java
similarity index 96%
rename from VectorTileMap/src/org/osmdroid/location/GeoNamesPOIProvider.java
rename to TileMapApp/src/org/osmdroid/location/GeoNamesPOIProvider.java
index 510924f..bd3eada 100644
--- a/VectorTileMap/src/org/osmdroid/location/GeoNamesPOIProvider.java
+++ b/TileMapApp/src/org/osmdroid/location/GeoNamesPOIProvider.java
@@ -1,219 +1,219 @@
-package org.osmdroid.location;
-
-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;
-
-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.xml.sax.Attributes;
-import org.xml.sax.SAXException;
-import org.xml.sax.helpers.DefaultHandler;
-
-import android.util.Log;
-
-/**
- * POI Provider using GeoNames services. Currently, "find Nearby Wikipedia" and
- * "Wikipedia Articles in Bounding Box" services.
- * @see "http://www.geonames.org"
- * @author M.Kergall
- */
-public class GeoNamesPOIProvider {
-
- 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 getThem(String fullUrl) {
- Log.d(BonusPackHelper.LOG_TAG, "GeoNamesPOIProvider:get:" + fullUrl);
- String jString = BonusPackHelper.requestStringFromUrl(fullUrl);
- if (jString == null) {
- Log.e(BonusPackHelper.LOG_TAG, "GeoNamesPOIProvider: request failed.");
- return null;
- }
- try {
- JSONObject jRoot = new JSONObject(jString);
- JSONArray jPlaceIds = jRoot.getJSONArray("geonames");
- int n = jPlaceIds.length();
- ArrayList pois = new ArrayList(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.d(BonusPackHelper.LOG_TAG, "done");
- return pois;
- } catch (JSONException e) {
- e.printStackTrace();
- return null;
- }
- }
-
- //XML parsing seems 2 times slower than JSON parsing
- public ArrayList getThemXML(String fullUrl) {
- Log.d(BonusPackHelper.LOG_TAG, "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.d(BonusPackHelper.LOG_TAG, "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 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 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 mPOIs;
-
- public GeoNamesXMLHandler() {
- mPOIs = new ArrayList();
- }
-
- @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);
- }
- }
-
-}
+package org.osmdroid.location;
+
+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;
+
+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.xml.sax.Attributes;
+import org.xml.sax.SAXException;
+import org.xml.sax.helpers.DefaultHandler;
+
+import android.util.Log;
+
+/**
+ * POI Provider using GeoNames services. Currently, "find Nearby Wikipedia" and
+ * "Wikipedia Articles in Bounding Box" services.
+ * @see "http://www.geonames.org"
+ * @author M.Kergall
+ */
+public class GeoNamesPOIProvider {
+
+ 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 getThem(String fullUrl) {
+ Log.d(BonusPackHelper.LOG_TAG, "GeoNamesPOIProvider:get:" + fullUrl);
+ String jString = BonusPackHelper.requestStringFromUrl(fullUrl);
+ if (jString == null) {
+ Log.e(BonusPackHelper.LOG_TAG, "GeoNamesPOIProvider: request failed.");
+ return null;
+ }
+ try {
+ JSONObject jRoot = new JSONObject(jString);
+ JSONArray jPlaceIds = jRoot.getJSONArray("geonames");
+ int n = jPlaceIds.length();
+ ArrayList pois = new ArrayList(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.d(BonusPackHelper.LOG_TAG, "done");
+ return pois;
+ } catch (JSONException e) {
+ e.printStackTrace();
+ return null;
+ }
+ }
+
+ //XML parsing seems 2 times slower than JSON parsing
+ public ArrayList getThemXML(String fullUrl) {
+ Log.d(BonusPackHelper.LOG_TAG, "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.d(BonusPackHelper.LOG_TAG, "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 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 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 mPOIs;
+
+ public GeoNamesXMLHandler() {
+ mPOIs = new ArrayList();
+ }
+
+ @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);
+ }
+ }
+
+}
diff --git a/VectorTileMap/src/org/osmdroid/location/GeocoderNominatim.java b/TileMapApp/src/org/osmdroid/location/GeocoderNominatim.java
similarity index 95%
rename from VectorTileMap/src/org/osmdroid/location/GeocoderNominatim.java
rename to TileMapApp/src/org/osmdroid/location/GeocoderNominatim.java
index 9577d1e..1249f8b 100644
--- a/VectorTileMap/src/org/osmdroid/location/GeocoderNominatim.java
+++ b/TileMapApp/src/org/osmdroid/location/GeocoderNominatim.java
@@ -1,215 +1,210 @@
-package org.osmdroid.location;
-
-import java.io.IOException;
-import java.net.URLEncoder;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Locale;
-
-import org.json.JSONArray;
-import org.json.JSONException;
-import org.json.JSONObject;
-import org.osmdroid.utils.BonusPackHelper;
-
-import android.content.Context;
-import android.location.Address;
-import android.util.Log;
-
-/**
- * Implements an equivalent to Android Geocoder class, based on OpenStreetMap
- * data and Nominatim API.
- * See http://wiki.openstreetmap.org/wiki/Nominatim or
- * http://open.mapquestapi.com/nominatim/
- *
- * @author M.Kergall
- */
-public class GeocoderNominatim {
- 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 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.d(BonusPackHelper.LOG_TAG, "GeocoderNominatim::getFromLocation:" + url);
- String result = BonusPackHelper.requestStringFromUrl(url);
- //Log.d("NOMINATIM", result);
- if (result == null)
- throw new IOException();
- try {
- JSONObject jResult = new JSONObject(result);
- Address gAddress = buildAndroidAddress(jResult);
- List list = new ArrayList();
- list.add(gAddress);
- return list;
- } catch (JSONException e) {
- throw new IOException();
- }
- }
-
- public List 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);
- if (lowerLeftLatitude != 0.0 && lowerLeftLongitude != 0.0) {
- //viewbox = left, top, right, bottom:
- url += "&viewbox=" + lowerLeftLongitude
- + "," + upperRightLatitude
- + "," + upperRightLongitude
- + "," + lowerLeftLatitude
- + "&bounded=1";
- }
- Log.d(BonusPackHelper.LOG_TAG, "GeocoderNominatim::getFromLocationName:" + url);
- String result = BonusPackHelper.requestStringFromUrl(url);
- //Log.d(BonusPackHelper.LOG_TAG, result);
- if (result == null)
- throw new IOException();
- try {
- JSONArray jResults = new JSONArray(result);
- List list = new ArrayList();
- 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 getFromLocationName(String locationName, int maxResults)
- throws IOException {
- return getFromLocationName(locationName, maxResults, 0.0, 0.0, 0.0, 0.0);
- }
-
-}
+package org.osmdroid.location;
+
+import java.io.IOException;
+import java.net.URLEncoder;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Locale;
+
+import org.json.JSONArray;
+import org.json.JSONException;
+import org.json.JSONObject;
+import org.osmdroid.utils.BonusPackHelper;
+
+import android.content.Context;
+import android.location.Address;
+import android.util.Log;
+
+/**
+ * Implements an equivalent to Android Geocoder class, based on OpenStreetMap
+ * data and Nominatim API.
+ * See http://wiki.openstreetmap.org/wiki/Nominatim or
+ * http://open.mapquestapi.com/nominatim/
+ * @author M.Kergall
+ */
+public class GeocoderNominatim {
+ 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 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.d(BonusPackHelper.LOG_TAG, "GeocoderNominatim::getFromLocation:" + url);
+ String result = BonusPackHelper.requestStringFromUrl(url);
+ //Log.d("NOMINATIM", result);
+ if (result == null)
+ throw new IOException();
+ try {
+ JSONObject jResult = new JSONObject(result);
+ Address gAddress = buildAndroidAddress(jResult);
+ List list = new ArrayList();
+ list.add(gAddress);
+ return list;
+ } catch (JSONException e) {
+ throw new IOException();
+ }
+ }
+
+ public List 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);
+ if (lowerLeftLatitude != 0.0 && lowerLeftLongitude != 0.0) {
+ //viewbox = left, top, right, bottom:
+ url += "&viewbox=" + lowerLeftLongitude
+ + "," + upperRightLatitude
+ + "," + upperRightLongitude
+ + "," + lowerLeftLatitude
+ + "&bounded=1";
+ }
+ Log.d(BonusPackHelper.LOG_TAG, "GeocoderNominatim::getFromLocationName:" + url);
+ String result = BonusPackHelper.requestStringFromUrl(url);
+ //Log.d(BonusPackHelper.LOG_TAG, result);
+ if (result == null)
+ throw new IOException();
+ try {
+ JSONArray jResults = new JSONArray(result);
+ List list = new ArrayList();
+ 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 getFromLocationName(String locationName, int maxResults)
+ throws IOException {
+ return getFromLocationName(locationName, maxResults, 0.0, 0.0, 0.0, 0.0);
+ }
+
+}
diff --git a/VectorTileMap/src/org/osmdroid/location/NominatimPOIProvider.java b/TileMapApp/src/org/osmdroid/location/NominatimPOIProvider.java
similarity index 86%
rename from VectorTileMap/src/org/osmdroid/location/NominatimPOIProvider.java
rename to TileMapApp/src/org/osmdroid/location/NominatimPOIProvider.java
index 3dc88c7..2d6856f 100644
--- a/VectorTileMap/src/org/osmdroid/location/NominatimPOIProvider.java
+++ b/TileMapApp/src/org/osmdroid/location/NominatimPOIProvider.java
@@ -1,184 +1,199 @@
-package org.osmdroid.location;
-
-import java.net.URLEncoder;
-import java.util.ArrayList;
-
-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 android.graphics.Bitmap;
-import android.util.Log;
-
-/**
- * POI Provider using Nominatim service.
- * See https://wiki.openstreetmap.org/wiki/Nominatim
- * and http://open.mapquestapi.com/nominatim/
- *
- * @author M.Kergall
- */
-public class NominatimPOIProvider {
- /*
- * 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)
- * format=jsonv2 to get a place_rank offset= to offset the result ?...
- * polygon=1 to get the border of the poi as a polygon nearlat &
- * nearlon = ??? routewidth/69 and routewidth/30 ???
- */
- 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;
- }
-
- 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 getThem(String url) {
- Log.d(BonusPackHelper.LOG_TAG, "NominatimPOIProvider:get:" + url);
- String jString = BonusPackHelper.requestStringFromUrl(url);
- if (jString == null) {
- Log.e(BonusPackHelper.LOG_TAG, "NominatimPOIProvider: request failed.");
- return null;
- }
- try {
- JSONArray jPlaceIds = new JSONArray(jString);
- int n = jPlaceIds.length();
- ArrayList pois = new ArrayList(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.optLong("osm_id");
- poi.location = new GeoPoint(jPlace.getDouble("lat"), jPlace.getDouble("lon"));
- 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 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 getPOIInside(BoundingBox boundingBox, String type, int maxResults) {
- String url = getUrlInside(boundingBox, type, maxResults);
- 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 getPOIAlong(ArrayList 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());
- }
-}
+package org.osmdroid.location;
+
+import java.net.URLEncoder;
+import java.util.ArrayList;
+
+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 android.graphics.Bitmap;
+import android.util.Log;
+
+/**
+ * POI Provider using Nominatim service.
+ * See https://wiki.openstreetmap.org/wiki/Nominatim
+ * and http://open.mapquestapi.com/nominatim/
+ * @author M.Kergall
+ */
+public class NominatimPOIProvider implements POIProvider {
+ /* 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)
+ * format=jsonv2 to get a place_rank offset= to offset the result ?...
+ * polygon=1 to get the border of the poi as a polygon nearlat &
+ * nearlon = ??? routewidth/69 and routewidth/30 ??? */
+ 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 getThem(String url) {
+ Log.d(BonusPackHelper.LOG_TAG, "NominatimPOIProvider:get:" + url);
+ String jString = BonusPackHelper.requestStringFromUrl(url);
+ if (jString == null) {
+ Log.e(BonusPackHelper.LOG_TAG, "NominatimPOIProvider: request failed.");
+ return null;
+ }
+ try {
+ JSONArray jPlaceIds = new JSONArray(jString);
+ int n = jPlaceIds.length();
+ ArrayList pois = new ArrayList(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.d("NominatimPOIProvider", "could not parse " + bbox);
+ }
+ //Log.d("NominatimPOIProvider", "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 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 getPOIInside(BoundingBox boundingBox, String type, int maxResults) {
+ String url = getUrlInside(boundingBox, type, maxResults);
+ return getThem(url);
+ }
+
+ public ArrayList 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 getPOIAlong(ArrayList 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());
+ }
+}
diff --git a/VectorTileMap/src/org/osmdroid/location/POI.java b/TileMapApp/src/org/osmdroid/location/POI.java
similarity index 94%
rename from VectorTileMap/src/org/osmdroid/location/POI.java
rename to TileMapApp/src/org/osmdroid/location/POI.java
index 41e1771..43811e1 100644
--- a/VectorTileMap/src/org/osmdroid/location/POI.java
+++ b/TileMapApp/src/org/osmdroid/location/POI.java
@@ -1,177 +1,184 @@
-package org.osmdroid.location;
-
-import org.oscim.app.R;
-import org.oscim.core.GeoPoint;
-import org.osmdroid.utils.BonusPackHelper;
-
-import android.graphics.Bitmap;
-import android.os.AsyncTask;
-import android.os.Parcel;
-import android.os.Parcelable;
-import android.util.Log;
-import android.view.View;
-import android.widget.ImageView;
-
-/**
- * Point of Interest. Exact content may depend of the POI provider used.
- * @see NominatimPOIProvider
- * @see GeoNamesPOIProvider
- * @author M.Kergall
- */
-public class POI implements Parcelable {
- /** 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;
-
- /** Identifies the service provider of this POI. */
- public int serviceId;
- /** Nominatim: OSM ID. GeoNames: 0 */
- public long id;
- /** location of the POI */
- public GeoPoint location;
- /** 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) {
- Log.d(BonusPackHelper.LOG_TAG, "POI:load thumbnail:" + thumbnailPath);
- 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);
- new ThumbnailTask(imageView).execute(imageView);
- } else {
- imageView.setVisibility(View.GONE);
- }
- }
-
- class ThumbnailTask extends AsyncTask {
-
- public ThumbnailTask(ImageView iv) {
- iv.setTag(thumbnailPath);
- }
-
- @Override
- protected ImageView doInBackground(ImageView... params) {
- getThumbnail();
- return params[0];
- }
-
- @Override
- protected void onPostExecute(ImageView iv) {
- 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.writeLong(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 CREATOR = new Parcelable.Creator() {
- @Override
- public POI createFromParcel(Parcel in) {
- POI poi = new POI(in.readInt());
- poi.id = in.readLong();
- 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();
- // }
-}
+package org.osmdroid.location;
+
+import org.oscim.app.R;
+import org.oscim.core.BoundingBox;
+import org.oscim.core.GeoPoint;
+import org.osmdroid.utils.BonusPackHelper;
+
+import android.graphics.Bitmap;
+import android.os.AsyncTask;
+import android.os.Parcel;
+import android.os.Parcelable;
+import android.util.Log;
+import android.view.View;
+import android.widget.ImageView;
+
+/**
+ * Point of Interest. Exact content may depend of the POI provider used.
+ * @see NominatimPOIProvider
+ * @see GeoNamesPOIProvider
+ * @author M.Kergall
+ */
+public class POI implements Parcelable {
+ /** 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) {
+ Log.d(BonusPackHelper.LOG_TAG, "POI:load thumbnail:" + thumbnailPath);
+ 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 {
+
+ 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 CREATOR = new Parcelable.Creator() {
+ @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();
+ // }
+}
diff --git a/TileMapApp/src/org/osmdroid/location/POIProvider.java b/TileMapApp/src/org/osmdroid/location/POIProvider.java
new file mode 100644
index 0000000..51b98de
--- /dev/null
+++ b/TileMapApp/src/org/osmdroid/location/POIProvider.java
@@ -0,0 +1,9 @@
+package org.osmdroid.location;
+
+import java.util.List;
+
+import org.oscim.core.BoundingBox;
+
+public interface POIProvider {
+ public List getPOIInside(BoundingBox boundingBox, String query, int maxResults);
+}
diff --git a/VectorTileMap/src/org/osmdroid/location/PicasaPOIProvider.java b/TileMapApp/src/org/osmdroid/location/PicasaPOIProvider.java
similarity index 90%
rename from VectorTileMap/src/org/osmdroid/location/PicasaPOIProvider.java
rename to TileMapApp/src/org/osmdroid/location/PicasaPOIProvider.java
index 7ddfa7a..6509fa3 100644
--- a/VectorTileMap/src/org/osmdroid/location/PicasaPOIProvider.java
+++ b/TileMapApp/src/org/osmdroid/location/PicasaPOIProvider.java
@@ -1,155 +1,163 @@
-package org.osmdroid.location;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.net.URLEncoder;
-import java.util.ArrayList;
-
-import javax.xml.parsers.ParserConfigurationException;
-import javax.xml.parsers.SAXParser;
-import javax.xml.parsers.SAXParserFactory;
-
-import org.oscim.core.BoundingBox;
-import org.oscim.core.GeoPoint;
-import org.osmdroid.utils.BonusPackHelper;
-import org.osmdroid.utils.HttpConnection;
-import org.xml.sax.Attributes;
-import org.xml.sax.SAXException;
-import org.xml.sax.helpers.DefaultHandler;
-
-import android.util.Log;
-
-/** POI Provider using Picasa service.
- * @see "https://developers.google.com/picasa-web/docs/2.0/reference"
- * @author M.Kergall */
-public class PicasaPOIProvider {
-
- 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;
- }
-
- 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 getThem(String fullUrl) {
- Log.d(BonusPackHelper.LOG_TAG, "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.d(BonusPackHelper.LOG_TAG, "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 ArrayList getPOIInside(BoundingBox boundingBox, int maxResults, String query) {
- String url = getUrlInside(boundingBox, maxResults, query);
- return getThem(url);
- }
-}
-
-class PicasaXMLHandler extends DefaultHandler {
-
- private String mString;
- double mLat, mLng;
- POI mPOI;
- ArrayList mPOIs;
- int mTotalResults;
-
- public PicasaXMLHandler() {
- mPOIs = new ArrayList();
- }
-
- @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 = Long.parseLong(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);
- }
- }
-
-}
+package org.osmdroid.location;
+
+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;
+
+import org.oscim.core.BoundingBox;
+import org.oscim.core.GeoPoint;
+import org.osmdroid.utils.BonusPackHelper;
+import org.osmdroid.utils.HttpConnection;
+import org.xml.sax.Attributes;
+import org.xml.sax.SAXException;
+import org.xml.sax.helpers.DefaultHandler;
+
+import android.util.Log;
+
+/**
+ * POI Provider using Picasa service.
+ * @see "https://developers.google.com/picasa-web/docs/2.0/reference"
+ * @author M.Kergall
+ */
+public class PicasaPOIProvider implements POIProvider {
+
+ 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 getThem(String fullUrl) {
+ Log.d(BonusPackHelper.LOG_TAG, "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.d(BonusPackHelper.LOG_TAG, "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 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 mPOIs;
+ int mTotalResults;
+
+ public PicasaXMLHandler() {
+ mPOIs = new ArrayList();
+ }
+
+ @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);
+ }
+ }
+
+}
diff --git a/VectorTileMap/src/org/osmdroid/overlays/DefaultInfoWindow.java b/TileMapApp/src/org/osmdroid/overlays/DefaultInfoWindow.java
similarity index 96%
rename from VectorTileMap/src/org/osmdroid/overlays/DefaultInfoWindow.java
rename to TileMapApp/src/org/osmdroid/overlays/DefaultInfoWindow.java
index 4af06fa..1186d45 100644
--- a/VectorTileMap/src/org/osmdroid/overlays/DefaultInfoWindow.java
+++ b/TileMapApp/src/org/osmdroid/overlays/DefaultInfoWindow.java
@@ -1,100 +1,99 @@
-package org.osmdroid.overlays;
-
-import org.oscim.view.MapView;
-import org.osmdroid.utils.BonusPackHelper;
-
-import android.content.Context;
-import android.graphics.drawable.Drawable;
-import android.util.Log;
-import android.view.View;
-import android.widget.ImageView;
-import android.widget.TextView;
-
-/**
- * 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();
- mTitleId = context.getResources().getIdentifier("id/bubble_title", null, packageName);
-
- mDescriptionId = context.getResources().getIdentifier("id/bubble_description", null,
- packageName);
-
- mSubDescriptionId = context.getResources().getIdentifier("id/bubble_subdescription", null,
- packageName);
-
- mImageId = context.getResources().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(mapView.getContext());
-
- // 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(ExtendedOverlayItem 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
- }
-
-}
+package org.osmdroid.overlays;
+
+import org.oscim.view.MapView;
+import org.osmdroid.utils.BonusPackHelper;
+
+import android.content.Context;
+import android.graphics.drawable.Drawable;
+import android.util.Log;
+import android.view.View;
+import android.widget.ImageView;
+import android.widget.TextView;
+
+/**
+ * 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();
+ mTitleId = context.getResources().getIdentifier("id/bubble_title", null, packageName);
+
+ mDescriptionId = context.getResources().getIdentifier("id/bubble_description", null,
+ packageName);
+
+ mSubDescriptionId = context.getResources().getIdentifier("id/bubble_subdescription", null,
+ packageName);
+
+ mImageId = context.getResources().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(mapView.getContext());
+
+ // 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(ExtendedOverlayItem 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
+ }
+
+}
diff --git a/VectorTileMap/src/org/osmdroid/overlays/ExtendedOverlayItem.java b/TileMapApp/src/org/osmdroid/overlays/ExtendedOverlayItem.java
similarity index 83%
rename from VectorTileMap/src/org/osmdroid/overlays/ExtendedOverlayItem.java
rename to TileMapApp/src/org/osmdroid/overlays/ExtendedOverlayItem.java
index 09deda7..89f00e6 100644
--- a/VectorTileMap/src/org/osmdroid/overlays/ExtendedOverlayItem.java
+++ b/TileMapApp/src/org/osmdroid/overlays/ExtendedOverlayItem.java
@@ -1,168 +1,168 @@
-package org.osmdroid.overlays;
-
-import org.oscim.core.GeoPoint;
-import org.oscim.overlay.OverlayItem;
-import org.oscim.view.MapView;
-
-import android.graphics.Point;
-import android.graphics.drawable.Drawable;
-
-/**
- * An OverlayItem to use in ItemizedOverlayWithBubble
- * - more complete: can contain an image and a sub-description that will be
- * displayed in the bubble,
- * - and flexible: attributes are modifiable
- * Known Issues:
- * - Bubble offset is not perfect on h&xhdpi resolutions, due to an osmdroid
- * issue on marker drawing
- * - Bubble offset is at 0 when using the default marker => set the marker on
- * each item!
- * @see ItemizedOverlayWithBubble
- * @author M.Kergall
- */
-public class ExtendedOverlayItem extends OverlayItem {
-
- // 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 ExtendedOverlayItem(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;
- }
-
- /**
- * From a HotspotPlace and drawable dimensions (width, height), return the
- * hotspot position. Could be a public method of HotspotPlace or
- * OverlayItem...
- * @param place
- * ...
- * @param w
- * ...
- * @param h
- * ...
- * @return ...
- */
- public Point getHotspot(HotspotPlace place, int w, int h) {
- Point hp = new Point();
- if (place == null)
- place = HotspotPlace.BOTTOM_CENTER; // use same default than in
- // osmdroid.
- switch (place) {
- case NONE:
- hp.set(0, 0);
- break;
- case BOTTOM_CENTER:
- hp.set(w / 2, 0);
- break;
- case LOWER_LEFT_CORNER:
- hp.set(0, 0);
- break;
- case LOWER_RIGHT_CORNER:
- hp.set(w, 0);
- break;
- case CENTER:
- hp.set(w / 2, -h / 2);
- break;
- case LEFT_CENTER:
- hp.set(0, -h / 2);
- break;
- case RIGHT_CENTER:
- hp.set(w, -h / 2);
- break;
- case TOP_CENTER:
- hp.set(w / 2, -h);
- break;
- case UPPER_LEFT_CORNER:
- hp.set(0, -h);
- break;
- case UPPER_RIGHT_CORNER:
- hp.set(w, -h);
- break;
- }
- return hp;
- }
-
- /**
- * Populates this bubble with all item info:
- *
- * title and description in any case,
- *
- *
- * image and sub-description if any.
- *
- * and centers the map on the item.
- * @param bubble
- * ...
- * @param mapView
- * ...
- */
- public void showBubble(InfoWindow bubble, MapView mapView) {
- // 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);
- }
-}
+package org.osmdroid.overlays;
+
+import org.oscim.core.GeoPoint;
+import org.oscim.overlay.OverlayItem;
+import org.oscim.view.MapView;
+
+import android.graphics.Point;
+import android.graphics.drawable.Drawable;
+
+/**
+ * An OverlayItem to use in ItemizedOverlayWithBubble
+ * - more complete: can contain an image and a sub-description that will be
+ * displayed in the bubble,
+ * - and flexible: attributes are modifiable
+ * Known Issues:
+ * - Bubble offset is not perfect on h&xhdpi resolutions, due to an osmdroid
+ * issue on marker drawing
+ * - Bubble offset is at 0 when using the default marker => set the marker on
+ * each item!
+ * @see ItemizedOverlayWithBubble
+ * @author M.Kergall
+ */
+public class ExtendedOverlayItem extends OverlayItem {
+
+ // 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 ExtendedOverlayItem(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;
+ }
+
+ /**
+ * From a HotspotPlace and drawable dimensions (width, height), return the
+ * hotspot position. Could be a public method of HotspotPlace or
+ * OverlayItem...
+ * @param place
+ * ...
+ * @param w
+ * ...
+ * @param h
+ * ...
+ * @return ...
+ */
+ public Point getHotspot(HotspotPlace place, int w, int h) {
+ Point hp = new Point();
+ if (place == null)
+ place = HotspotPlace.BOTTOM_CENTER; // use same default than in
+ // osmdroid.
+ switch (place) {
+ case NONE:
+ hp.set(0, 0);
+ break;
+ case BOTTOM_CENTER:
+ hp.set(w / 2, 0);
+ break;
+ case LOWER_LEFT_CORNER:
+ hp.set(0, 0);
+ break;
+ case LOWER_RIGHT_CORNER:
+ hp.set(w, 0);
+ break;
+ case CENTER:
+ hp.set(w / 2, -h / 2);
+ break;
+ case LEFT_CENTER:
+ hp.set(0, -h / 2);
+ break;
+ case RIGHT_CENTER:
+ hp.set(w, -h / 2);
+ break;
+ case TOP_CENTER:
+ hp.set(w / 2, -h);
+ break;
+ case UPPER_LEFT_CORNER:
+ hp.set(0, -h);
+ break;
+ case UPPER_RIGHT_CORNER:
+ hp.set(w, -h);
+ break;
+ }
+ return hp;
+ }
+
+ /**
+ * Populates this bubble with all item info:
+ *
+ * title and description in any case,
+ *
+ *
+ * image and sub-description if any.
+ *
+ * and centers the map on the item.
+ * @param bubble
+ * ...
+ * @param mapView
+ * ...
+ */
+ public void showBubble(InfoWindow bubble, MapView mapView) {
+ // 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);
+ }
+}
diff --git a/VectorTileMap/src/org/osmdroid/overlays/InfoWindow.java b/TileMapApp/src/org/osmdroid/overlays/InfoWindow.java
similarity index 96%
rename from VectorTileMap/src/org/osmdroid/overlays/InfoWindow.java
rename to TileMapApp/src/org/osmdroid/overlays/InfoWindow.java
index 7a318f9..d2516aa 100644
--- a/VectorTileMap/src/org/osmdroid/overlays/InfoWindow.java
+++ b/TileMapApp/src/org/osmdroid/overlays/InfoWindow.java
@@ -1,140 +1,140 @@
-package org.osmdroid.overlays;
-
-// TODO composite view as texture overlay and only allow one bubble at a time.
-
-import org.oscim.view.MapView;
-
-import android.content.Context;
-import android.view.Gravity;
-import android.view.LayoutInflater;
-import android.view.View;
-import android.view.ViewGroup;
-import android.widget.RelativeLayout;
-
-/**
- * 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:
- *
- * Structure and content of the view is let to the responsibility of the
- * caller.
- * The same InfoWindow can be associated to many items.
- *
- * Known issues:
- *
- * It disappears when zooming in/out (osmdroid issue #259 on osmdroid 3.0.8,
- * should be fixed in next version).
- * The window is displayed "above" the marker, so the queue of the bubble
- * can hide the marker.
- *
- * This is an abstract class.
- * @see DefaultInfoWindow
- * @author M.Kergall
- */
-public abstract class InfoWindow {
-
- protected View mView;
- protected boolean mIsVisible = false;
- protected MapView mMapView;
- protected RelativeLayout mLayout;
- private android.widget.RelativeLayout.LayoutParams mLayoutPos;
-
- /**
- * @param layoutResId
- * the id of the view resource.
- * @param mapView
- * the mapview on which is hooked the view
- */
- public InfoWindow(int layoutResId, MapView mapView) {
- mMapView = mapView;
-
- mIsVisible = false;
- 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.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM);
- mLayout.setLayoutParams(rlp);
- mLayoutPos = rlp;
-
- // not so sure about this. why is just blitting the bitmap on glview so slow?...
- mView.setDrawingCacheEnabled(true);
- // mLayout.setDrawingCacheEnabled(true);
- // mLayout.setPersistentDrawingCache(ViewGroup.PERSISTENT_ALL_CACHES);
- // mLayout.setAlwaysDrawnWithCacheEnabled(true); // call this method
- mLayout.setWillNotDraw(true);
- mLayout.addView(mView);
- }
-
- /**
- * Returns the Android view. This allows to set its content.
- * @return the Android view
- */
- public View getView() {
- return (mView);
- }
-
- /**
- * 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(ExtendedOverlayItem item, int offsetX, int offsetY) {
- onOpen(item);
-
- close(); // if it was already opened
- // mView.requestLayout();
- mView.buildDrawingCache();
- mMapView.addView(mLayout);
- mIsVisible = true;
- }
-
- public void position(int x, int y) {
- // if this isnt madness...
- RelativeLayout.LayoutParams rlp = mLayoutPos;
- rlp.leftMargin = x;
- rlp.rightMargin = -x;
- rlp.topMargin = -y;
- rlp.bottomMargin = y + mMapView.getHeight() / 2;
- mLayout.setLayoutParams(rlp);
-
- //mMapView.requestLayout();
- mLayout.requestLayout();
-
- // using scrollTo the bubble somehow does not appear when it
- // is not already in viewport...
- // mLayout.scrollTo(-x, y + mMapView.getHeight() / 2);
- }
-
- public void close() {
- if (mIsVisible) {
- mIsVisible = false;
- ((ViewGroup) mLayout.getParent()).removeView(mLayout);
- onClose();
- }
- }
-
- public boolean isOpen() {
- return mIsVisible;
- }
-
- // Abstract methods to implement:
- public abstract void onOpen(ExtendedOverlayItem item);
-
- public abstract void onClose();
-
-}
+package org.osmdroid.overlays;
+
+// TODO composite view as texture overlay and only allow one bubble at a time.
+
+import org.oscim.view.MapView;
+
+import android.content.Context;
+import android.view.Gravity;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.RelativeLayout;
+
+/**
+ * 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:
+ *
+ * Structure and content of the view is let to the responsibility of the
+ * caller.
+ * The same InfoWindow can be associated to many items.
+ *
+ * Known issues:
+ *
+ * It disappears when zooming in/out (osmdroid issue #259 on osmdroid 3.0.8,
+ * should be fixed in next version).
+ * The window is displayed "above" the marker, so the queue of the bubble
+ * can hide the marker.
+ *
+ * This is an abstract class.
+ * @see DefaultInfoWindow
+ * @author M.Kergall
+ */
+public abstract class InfoWindow {
+
+ protected View mView;
+ protected boolean mIsVisible = false;
+ protected MapView mMapView;
+ protected RelativeLayout mLayout;
+ private android.widget.RelativeLayout.LayoutParams mLayoutPos;
+
+ /**
+ * @param layoutResId
+ * the id of the view resource.
+ * @param mapView
+ * the mapview on which is hooked the view
+ */
+ public InfoWindow(int layoutResId, MapView mapView) {
+ mMapView = mapView;
+
+ mIsVisible = false;
+ 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.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM);
+ mLayout.setLayoutParams(rlp);
+ mLayoutPos = rlp;
+
+ // not so sure about this. why is just blitting the bitmap on glview so slow?...
+ mView.setDrawingCacheEnabled(true);
+ // mLayout.setDrawingCacheEnabled(true);
+ // mLayout.setPersistentDrawingCache(ViewGroup.PERSISTENT_ALL_CACHES);
+ // mLayout.setAlwaysDrawnWithCacheEnabled(true); // call this method
+ mLayout.setWillNotDraw(true);
+ mLayout.addView(mView);
+ }
+
+ /**
+ * Returns the Android view. This allows to set its content.
+ * @return the Android view
+ */
+ public View getView() {
+ return (mView);
+ }
+
+ /**
+ * 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(ExtendedOverlayItem item, int offsetX, int offsetY) {
+ onOpen(item);
+
+ close(); // if it was already opened
+ // mView.requestLayout();
+ mView.buildDrawingCache();
+ mMapView.addView(mLayout);
+ mIsVisible = true;
+ }
+
+ public void position(int x, int y) {
+ // if this isnt madness...
+ RelativeLayout.LayoutParams rlp = mLayoutPos;
+ rlp.leftMargin = x;
+ rlp.rightMargin = -x;
+ rlp.topMargin = -y;
+ rlp.bottomMargin = y + mMapView.getHeight() / 2;
+ mLayout.setLayoutParams(rlp);
+
+ //mMapView.requestLayout();
+ mLayout.requestLayout();
+
+ // using scrollTo the bubble somehow does not appear when it
+ // is not already in viewport...
+ // mLayout.scrollTo(-x, y + mMapView.getHeight() / 2);
+ }
+
+ public void close() {
+ if (mIsVisible) {
+ mIsVisible = false;
+ ((ViewGroup) mLayout.getParent()).removeView(mLayout);
+ onClose();
+ }
+ }
+
+ public boolean isOpen() {
+ return mIsVisible;
+ }
+
+ // Abstract methods to implement:
+ public abstract void onOpen(ExtendedOverlayItem item);
+
+ public abstract void onClose();
+
+}
diff --git a/VectorTileMap/src/org/osmdroid/overlays/ItemizedOverlayWithBubble.java b/TileMapApp/src/org/osmdroid/overlays/ItemizedOverlayWithBubble.java
similarity index 94%
rename from VectorTileMap/src/org/osmdroid/overlays/ItemizedOverlayWithBubble.java
rename to TileMapApp/src/org/osmdroid/overlays/ItemizedOverlayWithBubble.java
index 9ae127b..d9ac5a2 100644
--- a/VectorTileMap/src/org/osmdroid/overlays/ItemizedOverlayWithBubble.java
+++ b/TileMapApp/src/org/osmdroid/overlays/ItemizedOverlayWithBubble.java
@@ -1,199 +1,198 @@
-package org.osmdroid.overlays;
-
-import java.util.List;
-
-import org.oscim.core.GeoPoint;
-import org.oscim.core.MapPosition;
-import org.oscim.overlay.ItemizedIconOverlay;
-import org.oscim.overlay.OverlayItem;
-import org.oscim.view.MapView;
-import org.osmdroid.utils.BonusPackHelper;
-
-import android.content.Context;
-import android.graphics.Point;
-import android.util.Log;
-
-/**
- * An itemized overlay with an InfoWindow or "bubble" which opens when the user
- * taps on an overlay item, and displays item attributes.
- * Items must be ExtendedOverlayItem.
- * @see ExtendedOverlayItem
- * @see InfoWindow
- * @author M.Kergall
- * @param -
- * ...
- */
-public class ItemizedOverlayWithBubble
- extends ItemizedIconOverlay
-
- implements ItemizedIconOverlay.OnItemGestureListener
-
-{
-
- protected List
- mItemsList;
-
- // 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 OverlayItem mItemWithBubble;
-
- static int layoutResId = 0;
-
- @Override
- public boolean onItemLongPress(final int index, final OverlayItem item) {
- if (mBubble.isOpen())
- hideBubble();
- else
- showBubble(index);
- return false;
- }
-
- @Override
- public boolean onItemSingleTapUp(final int index, final OverlayItem item) {
- showBubble(index);
- return false;
- }
-
- private Point mTmpPoint = new Point();
-
- @Override
- public void onUpdate(MapPosition mapPosition) {
- if (mBubble.isOpen()) {
- GeoPoint gp = mItemWithBubble.getPoint();
- Point p = mTmpPoint;
-
- mMapView.getMapViewPosition().project(gp, p);
-
- mBubble.position(p.x, p.y);
- }
- }
-
- public ItemizedOverlayWithBubble(final MapView mapView, final Context context,
- final List
- aList, final InfoWindow bubble) {
-
- super(mapView, context, aList, null);
-
- mItemsList = aList;
- 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, mapView);
- }
- mItemWithBubble = null;
-
- mOnItemGestureListener = this;
- }
-
- public ItemizedOverlayWithBubble(final Context context, final List
- aList,
- final MapView mapView) {
- this(mapView, context, aList, null);
- }
-
- void showBubble(int index) {
- showBubbleOnItem(index, mMapView);
- }
-
- /**
- * 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
- * @param mapView
- * ...
- */
- public void showBubbleOnItem(final int index, final MapView mapView) {
- ExtendedOverlayItem eItem = (ExtendedOverlayItem) (getItem(index));
- mItemWithBubble = eItem;
- if (eItem != null) {
- eItem.showBubble(mBubble, mapView);
- // mMapView.getMapViewPosition().animateTo(eItem.mGeoPoint, 0);
-
- mapView.redrawMap();
- setFocus((Item) eItem);
- }
- }
-
- /** Close the bubble (if it's opened). */
- public void hideBubble() {
- mBubble.close();
- mItemWithBubble = null;
- }
-
- @Override
- protected boolean onSingleTapUpHelper(final int index, final Item item, final MapView mapView) {
- showBubbleOnItem(index, mapView);
- return true;
- }
-
- /** @return the item currenty showing the bubble, or null if none. */
- public OverlayItem 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() {
- OverlayItem item = getBubbledItem();
- if (item == null)
- return -1;
-
- return mItemsList.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();
- }
-
- // FIXME @Override
- // public void draw(final Canvas canvas, final MapView mapView, final boolean shadow) {
- // // 1. Fixing drawing focused item on top in ItemizedOverlay (osmdroid
- // // issue 354):
- // if (shadow) {
- // return;
- // }
- // final Projection pj = mapView.getProjection();
- // final int size = mItemsList.size() - 1;
- // final Point mCurScreenCoords = new Point();
- //
- // /*
- // * Draw in backward cycle, so the items with the least index are on the
- // * front.
- // */
- // for (int i = size; i >= 0; i--) {
- // final Item item = getItem(i);
- // if (item != mItemWithBubble) {
- // pj.toMapPixels(item.mGeoPoint, mCurScreenCoords);
- // onDrawItem(canvas, item, mCurScreenCoords);
- // }
- // }
- // // draw focused item last:
- // if (mItemWithBubble != null) {
- // pj.toMapPixels(mItemWithBubble.mGeoPoint, mCurScreenCoords);
- // onDrawItem(canvas, (Item) mItemWithBubble, mCurScreenCoords);
- // }
- // }
-
-}
+package org.osmdroid.overlays;
+
+import java.util.List;
+
+import org.oscim.core.GeoPoint;
+import org.oscim.core.MapPosition;
+import org.oscim.overlay.ItemizedIconOverlay;
+import org.oscim.overlay.OverlayItem;
+import org.oscim.view.MapView;
+import org.osmdroid.utils.BonusPackHelper;
+
+import android.content.Context;
+import android.graphics.Point;
+import android.util.Log;
+
+/**
+ * An itemized overlay with an InfoWindow or "bubble" which opens when the user
+ * taps on an overlay item, and displays item attributes.
+ * Items must be ExtendedOverlayItem.
+ * @see ExtendedOverlayItem
+ * @see InfoWindow
+ * @author M.Kergall
+ * @param -
+ * ...
+ */
+public class ItemizedOverlayWithBubble
- extends ItemizedIconOverlay
-
+ implements ItemizedIconOverlay.OnItemGestureListener
-
+{
+
+ protected List
- mItemsList;
+
+ // 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 OverlayItem mItemWithBubble;
+
+ static int layoutResId = 0;
+
+ @Override
+ public boolean onItemLongPress(final int index, final OverlayItem item) {
+ if (mBubble.isOpen())
+ hideBubble();
+ else
+ showBubble(index);
+ return false;
+ }
+
+ @Override
+ public boolean onItemSingleTapUp(final int index, final OverlayItem item) {
+ showBubble(index);
+ return false;
+ }
+
+ private Point mTmpPoint = new Point();
+
+ @Override
+ public void onUpdate(MapPosition mapPosition, boolean changed) {
+ if (mBubble.isOpen()) {
+ GeoPoint gp = mItemWithBubble.getPoint();
+
+ Point p = mTmpPoint;
+ mMapView.getMapViewPosition().project(gp, p);
+
+ mBubble.position(p.x, p.y);
+ }
+ }
+
+ public ItemizedOverlayWithBubble(final MapView mapView, final Context context,
+ final List
- aList, final InfoWindow bubble) {
+ super(mapView, context, aList, null);
+
+ mItemsList = aList;
+ 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, mapView);
+ }
+ mItemWithBubble = null;
+
+ mOnItemGestureListener = this;
+ }
+
+ public ItemizedOverlayWithBubble(final Context context, final List
- aList,
+ final MapView mapView) {
+ this(mapView, context, aList, null);
+ }
+
+ void showBubble(int index) {
+ showBubbleOnItem(index, mMapView);
+ }
+
+ /**
+ * 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
+ * @param mapView
+ * ...
+ */
+ public void showBubbleOnItem(final int index, final MapView mapView) {
+ ExtendedOverlayItem eItem = (ExtendedOverlayItem) (getItem(index));
+ mItemWithBubble = eItem;
+ if (eItem != null) {
+ eItem.showBubble(mBubble, mapView);
+ // mMapView.getMapViewPosition().animateTo(eItem.mGeoPoint, 0);
+
+ mapView.redrawMap(true);
+ setFocus((Item) eItem);
+ }
+ }
+
+ /** Close the bubble (if it's opened). */
+ public void hideBubble() {
+ mBubble.close();
+ mItemWithBubble = null;
+ }
+
+ @Override
+ protected boolean onSingleTapUpHelper(final int index, final Item item, final MapView mapView) {
+ showBubbleOnItem(index, mapView);
+ return true;
+ }
+
+ /** @return the item currenty showing the bubble, or null if none. */
+ public OverlayItem 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() {
+ OverlayItem item = getBubbledItem();
+ if (item == null)
+ return -1;
+
+ return mItemsList.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();
+ }
+
+ // FIXME @Override
+ // public void draw(final Canvas canvas, final MapView mapView, final boolean shadow) {
+ // // 1. Fixing drawing focused item on top in ItemizedOverlay (osmdroid
+ // // issue 354):
+ // if (shadow) {
+ // return;
+ // }
+ // final Projection pj = mapView.getProjection();
+ // final int size = mItemsList.size() - 1;
+ // final Point mCurScreenCoords = new Point();
+ //
+ // /*
+ // * Draw in backward cycle, so the items with the least index are on the
+ // * front.
+ // */
+ // for (int i = size; i >= 0; i--) {
+ // final Item item = getItem(i);
+ // if (item != mItemWithBubble) {
+ // pj.toMapPixels(item.mGeoPoint, mCurScreenCoords);
+ // onDrawItem(canvas, item, mCurScreenCoords);
+ // }
+ // }
+ // // draw focused item last:
+ // if (mItemWithBubble != null) {
+ // pj.toMapPixels(mItemWithBubble.mGeoPoint, mCurScreenCoords);
+ // onDrawItem(canvas, (Item) mItemWithBubble, mCurScreenCoords);
+ // }
+ // }
+
+}
diff --git a/TileMapApp/src/org/osmdroid/overlays/MapEventsOverlay.java b/TileMapApp/src/org/osmdroid/overlays/MapEventsOverlay.java
new file mode 100644
index 0000000..e4063f0
--- /dev/null
+++ b/TileMapApp/src/org/osmdroid/overlays/MapEventsOverlay.java
@@ -0,0 +1,48 @@
+package org.osmdroid.overlays;
+
+import org.oscim.core.GeoPoint;
+import org.oscim.overlay.Overlay;
+import org.oscim.view.MapView;
+
+import android.content.Context;
+import android.view.MotionEvent;
+
+/**
+ * Empty overlay than can be used to detect events on the map, and to throw them
+ * to a MapEventsReceiver.
+ * @see MapEventsReceiver
+ * @author M.Kergall
+ */
+public class MapEventsOverlay extends Overlay {
+
+ private MapEventsReceiver mReceiver;
+
+ /**
+ * @param mapView
+ * the MapView
+ * @param receiver
+ * the object that will receive/handle the events. It must
+ * implement MapEventsReceiver interface.
+ */
+ public MapEventsOverlay(MapView mapView, MapEventsReceiver receiver) {
+ super(mapView);
+ mReceiver = receiver;
+ }
+
+ @Override
+ public boolean onSingleTapUp(MotionEvent e) {
+ GeoPoint p = mMapView.getMapViewPosition().fromScreenPixels(e.getX(), e.getY());
+
+ return mReceiver.singleTapUpHelper(p);
+ }
+
+ @Override
+ public boolean onLongPress(MotionEvent e) {
+
+ GeoPoint p = mMapView.getMapViewPosition().fromScreenPixels(e.getX(), e.getY());
+
+ // throw event to the receiver:
+ return mReceiver.longPressHelper(p);
+ }
+
+}
diff --git a/VectorTileMap/src/org/osmdroid/overlays/MapEventsReceiver.java b/TileMapApp/src/org/osmdroid/overlays/MapEventsReceiver.java
similarity index 95%
rename from VectorTileMap/src/org/osmdroid/overlays/MapEventsReceiver.java
rename to TileMapApp/src/org/osmdroid/overlays/MapEventsReceiver.java
index c7b9289..017bef7 100644
--- a/VectorTileMap/src/org/osmdroid/overlays/MapEventsReceiver.java
+++ b/TileMapApp/src/org/osmdroid/overlays/MapEventsReceiver.java
@@ -1,29 +1,28 @@
-package org.osmdroid.overlays;
-
-import org.oscim.core.GeoPoint;
-
-/**
- * Interface for objects that need to handle map events thrown by a
- * MapEventsOverlay.
- *
- * @see 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);
-}
+package org.osmdroid.overlays;
+
+import org.oscim.core.GeoPoint;
+
+/**
+ * Interface for objects that need to handle map events thrown by a
+ * MapEventsOverlay.
+ * @see 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);
+}
diff --git a/TileMapApp/src/org/osmdroid/overlays/POIOverlay.java b/TileMapApp/src/org/osmdroid/overlays/POIOverlay.java
new file mode 100644
index 0000000..a351a9d
--- /dev/null
+++ b/TileMapApp/src/org/osmdroid/overlays/POIOverlay.java
@@ -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
.
+ */
+package org.osmdroid.overlays;
+
+import java.util.HashMap;
+import java.util.List;
+
+import org.oscim.app.R;
+import org.oscim.core.BoundingBox;
+import org.oscim.core.MapPosition;
+import org.oscim.overlay.OverlayItem;
+import org.oscim.view.MapView;
+import org.osmdroid.location.FlickrPOIProvider;
+import org.osmdroid.location.POI;
+import org.osmdroid.location.POIProvider;
+import org.osmdroid.utils.BonusPackHelper;
+
+import android.content.Context;
+import android.content.Intent;
+import android.graphics.drawable.Drawable;
+import android.net.Uri;
+import android.os.AsyncTask;
+import android.util.Log;
+import android.view.View;
+import android.widget.Button;
+import android.widget.ImageView;
+
+public class POIOverlay extends ItemizedOverlayWithBubble {
+
+ POIProvider mPoiProvider;
+ UpdateTask mUpdateTask;
+ boolean mTaskRunning;
+ Drawable mMarker;
+ BoundingBox mBoundingBox;
+
+ public POIOverlay(MapView mapView, Context context, List aList,
+ InfoWindow bubble) {
+ super(mapView, context, aList, bubble);
+
+ mUpdateTask = new UpdateTask();
+ FlickrPOIProvider provider = new FlickrPOIProvider("c39be46304a6c6efda8bc066c185cd7e");
+ provider.setPrevious(mPOIMap);
+
+ mPoiProvider = provider;
+ mMarker = context.getResources().getDrawable(R.drawable.marker_poi_flickr);
+ }
+
+ public void setPoiProvider(POIProvider poiProvider) {
+ mPoiProvider = poiProvider;
+ }
+
+ @Override
+ public void onUpdate(MapPosition mapPosition, boolean changed) {
+ super.onUpdate(mapPosition, changed);
+
+ if (changed && !mTaskRunning) {
+ mMapView.postDelayed(mUpdateTask, 1000);
+ mTaskRunning = true;
+ }
+ }
+
+ class UpdateTask implements Runnable {
+
+ @Override
+ public void run() {
+ mTaskRunning = false;
+
+ BoundingBox bb = mMapView.getBoundingBox();
+
+ if (mBoundingBox == null || !mBoundingBox.equals(bb)) {
+ // synchronized (mBoundingBox) {
+ mBoundingBox = bb;
+ // }
+
+ // check bounding box
+ Log.d(BonusPackHelper.LOG_TAG, " update pois");
+
+ new POITask().execute();
+ }
+ }
+ }
+
+ HashMap mPOIMap = new HashMap(100);
+
+ class POITask extends AsyncTask> {
+
+ @Override
+ protected List doInBackground(Object... params) {
+
+ return mPoiProvider.getPOIInside(mBoundingBox, "", 20);
+ }
+
+ @Override
+ protected void onPostExecute(List pois) {
+ // removeAllItems();
+
+ if (pois != null) {
+ for (POI poi : pois) {
+ ExtendedOverlayItem poiMarker = new ExtendedOverlayItem(poi.type,
+ poi.description, poi.location);
+
+ poiMarker.setMarker(mMarker);
+ poiMarker.setMarkerHotspot(OverlayItem.HotspotPlace.CENTER);
+ //thumbnail loading moved in POIInfoWindow.onOpen for better performances.
+ poiMarker.setRelatedObject(poi);
+
+ addItem(poiMarker);
+
+ mPOIMap.put(poi.id, poi);
+ }
+ }
+
+ mMapView.redrawMap(true);
+ }
+ }
+
+ public static class POIInfoWindow extends DefaultInfoWindow {
+
+ private Button mButton;
+ private ImageView mImage;
+
+ public POIInfoWindow(MapView mapView) {
+ super(R.layout.bonuspack_bubble, mapView);
+
+ mButton = (Button) mView.findViewById(R.id.bubble_moreinfo);
+ mImage = (ImageView) mView.findViewById(R.id.bubble_image);
+
+ //bonuspack_bubble layouts already contain a "more info" button.
+ mButton.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View view) {
+ POI poi = (POI) view.getTag();
+
+ if (poi != null && poi.url != null) {
+ Intent myIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(poi.url));
+ view.getContext().startActivity(myIntent);
+ }
+ }
+ });
+
+ // getView().setOnClickListener(new View.OnClickListener() {
+ // @Override
+ // public void onClick(View view) {
+ // POI poi = (POI) view.getTag();
+ //
+ // if (poi != null) {
+ // Intent intent = new Intent(tileMap, POIActivity.class);
+ // intent.putExtra("ID", poiMarkers.getBubbledItemId());
+ // tileMap.startActivityForResult(intent, TileMap.POIS_REQUEST);
+ // }
+ // }
+ // });
+ }
+
+ @Override
+ public void onOpen(ExtendedOverlayItem item) {
+ POI poi = (POI) item.getRelatedObject();
+
+ super.onOpen(item);
+
+ poi.fetchThumbnail(mImage);
+
+ //Show or hide "more info" button:
+ if (poi.url != null)
+ mButton.setVisibility(View.VISIBLE);
+ else
+ mButton.setVisibility(View.GONE);
+
+ mButton.setTag(poi);
+ getView().setTag(poi);
+ }
+ }
+
+}
diff --git a/VectorTileMap/src/org/osmdroid/routing/Road.java b/TileMapApp/src/org/osmdroid/routing/Road.java
similarity index 96%
rename from VectorTileMap/src/org/osmdroid/routing/Road.java
rename to TileMapApp/src/org/osmdroid/routing/Road.java
index 443ad61..508cea4 100644
--- a/VectorTileMap/src/org/osmdroid/routing/Road.java
+++ b/TileMapApp/src/org/osmdroid/routing/Road.java
@@ -1,240 +1,243 @@
-package org.osmdroid.routing;
-
-import java.util.ArrayList;
-
-import org.oscim.core.BoundingBox;
-import org.oscim.core.GeoPoint;
-import org.osmdroid.utils.BonusPackHelper;
-import org.osmdroid.utils.DouglasPeuckerReducer;
-
-import android.os.Parcel;
-import android.os.Parcelable;
-import android.util.Log;
-
-/**
- * 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)
- * @see MapQuestRoadManager
- * @see GoogleRoadManager
- * @see OSRMRoadManager
- * @author M.Kergall
- */
-public class Road implements Parcelable {
- /**
- * @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 ArrayList nodes;
- /** */
- /** there is one leg between each waypoint */
- public ArrayList legs;
- /** full shape: polyline, as an array of GeoPoints */
- public ArrayList routeHigh;
- /** the same, in low resolution (less points) */
- private ArrayList routeLow;
- /** road bounding box */
- public BoundingBox boundingBox;
-
- /** STATUS_INVALID = road not built */
- public static final int STATUS_INVALID = 0;
- /** STATUS_OK = road 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 road
- */
- public static final int STATUS_DEFAULT = 2;
-
- private void init() {
- status = STATUS_INVALID;
- length = 0.0;
- duration = 0.0;
- nodes = new ArrayList();
- routeHigh = new ArrayList();
- routeLow = null;
- legs = new ArrayList();
- boundingBox = null;
- }
-
- public Road() {
- init();
- }
-
- /**
- * default constructor when normal loading failed: the road shape only
- * contains the waypoints; All distances and times are at 0; there is no
- * node; status equals DEFAULT.
- * @param waypoints
- * ...
- */
- public Road(ArrayList 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++) {
- RoadLeg leg = new RoadLeg(/* i, i+1, mLinks */);
- legs.add(leg);
- }
- boundingBox = BoundingBox.fromGeoPoints(routeHigh);
- status = STATUS_DEFAULT;
- }
-
- /**
- * @return the road shape in "low resolution" = simplified by around 10
- * factor.
- */
- public ArrayList 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.d(BonusPackHelper.LOG_TAG, "Road reduced from " + n + " to " + routeLow.size()
- + " points");
- }
- return routeLow;
- }
-
- public void setRouteLow(ArrayList 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;
- }
-
- /**
- * @return length and duration of the whole road, or of a leg of the road,
- * as a String, in a readable format.
- * @param leg
- * leg index, starting from 0. -1 for the whole road
- */
- 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 road nodes.
- * 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(ArrayList waypoints) {
- legs = new ArrayList();
- 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 roadPoint = nodes.get(j).location;
- double dSquared = distanceLLSquared(roadPoint, waypoint);
- if (nodeIndexMin == -1 || dSquared < distanceMin) {
- distanceMin = dSquared;
- nodeIndexMin = j;
- }
- }
- // Build the leg as ending with this closest node:
- RoadLeg leg = new RoadLeg(firstNodeIndex, nodeIndexMin, nodes);
- legs.add(leg);
- firstNodeIndex = nodeIndexMin + 1; // restart next leg from end
- }
- // Build last leg ending with last node:
- RoadLeg lastLeg = new RoadLeg(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 CREATOR = new Parcelable.Creator() {
- @Override
- public Road createFromParcel(Parcel source) {
- return new Road(source);
- }
-
- @Override
- public Road[] newArray(int size) {
- return new Road[size];
- }
- };
-
- @SuppressWarnings("unchecked")
- private Road(Parcel in) {
- status = in.readInt();
- length = in.readDouble();
- duration = in.readDouble();
-
- nodes = in.readArrayList(RoadNode.class.getClassLoader());
- legs = in.readArrayList(RoadLeg.class.getClassLoader());
- routeHigh = in.readArrayList(GeoPoint.class.getClassLoader());
- boundingBox = in.readParcelable(BoundingBox.class.getClassLoader());
- }
-}
+package org.osmdroid.routing;
+
+import java.util.ArrayList;
+
+import org.oscim.core.BoundingBox;
+import org.oscim.core.GeoPoint;
+import org.osmdroid.routing.provider.GoogleRoadManager;
+import org.osmdroid.routing.provider.MapQuestRoadManager;
+import org.osmdroid.routing.provider.OSRMRoadManager;
+import org.osmdroid.utils.BonusPackHelper;
+import org.osmdroid.utils.DouglasPeuckerReducer;
+
+import android.os.Parcel;
+import android.os.Parcelable;
+import android.util.Log;
+
+/**
+ * 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)
+ * @see MapQuestRoadManager
+ * @see GoogleRoadManager
+ * @see OSRMRoadManager
+ * @author M.Kergall
+ */
+public class Road implements Parcelable {
+ /**
+ * @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 ArrayList nodes;
+ /** */
+ /** there is one leg between each waypoint */
+ public ArrayList legs;
+ /** full shape: polyline, as an array of GeoPoints */
+ public ArrayList routeHigh;
+ /** the same, in low resolution (less points) */
+ private ArrayList routeLow;
+ /** road bounding box */
+ public BoundingBox boundingBox;
+
+ /** STATUS_INVALID = road not built */
+ public static final int STATUS_INVALID = 0;
+ /** STATUS_OK = road 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 road
+ */
+ public static final int STATUS_DEFAULT = 2;
+
+ private void init() {
+ status = STATUS_INVALID;
+ length = 0.0;
+ duration = 0.0;
+ nodes = new ArrayList();
+ routeHigh = new ArrayList();
+ routeLow = null;
+ legs = new ArrayList();
+ boundingBox = null;
+ }
+
+ public Road() {
+ init();
+ }
+
+ /**
+ * default constructor when normal loading failed: the road shape only
+ * contains the waypoints; All distances and times are at 0; there is no
+ * node; status equals DEFAULT.
+ * @param waypoints
+ * ...
+ */
+ public Road(ArrayList 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++) {
+ RoadLeg leg = new RoadLeg(/* i, i+1, mLinks */);
+ legs.add(leg);
+ }
+ boundingBox = BoundingBox.fromGeoPoints(routeHigh);
+ status = STATUS_DEFAULT;
+ }
+
+ /**
+ * @return the road shape in "low resolution" = simplified by around 10
+ * factor.
+ */
+ public ArrayList 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.d(BonusPackHelper.LOG_TAG, "Road reduced from " + n + " to " + routeLow.size()
+ + " points");
+ }
+ return routeLow;
+ }
+
+ public void setRouteLow(ArrayList 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;
+ }
+
+ /**
+ * @return length and duration of the whole road, or of a leg of the road,
+ * as a String, in a readable format.
+ * @param leg
+ * leg index, starting from 0. -1 for the whole road
+ */
+ 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 road nodes.
+ * 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(ArrayList waypoints) {
+ legs = new ArrayList();
+ 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 roadPoint = nodes.get(j).location;
+ double dSquared = distanceLLSquared(roadPoint, waypoint);
+ if (nodeIndexMin == -1 || dSquared < distanceMin) {
+ distanceMin = dSquared;
+ nodeIndexMin = j;
+ }
+ }
+ // Build the leg as ending with this closest node:
+ RoadLeg leg = new RoadLeg(firstNodeIndex, nodeIndexMin, nodes);
+ legs.add(leg);
+ firstNodeIndex = nodeIndexMin + 1; // restart next leg from end
+ }
+ // Build last leg ending with last node:
+ RoadLeg lastLeg = new RoadLeg(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 CREATOR = new Parcelable.Creator() {
+ @Override
+ public Road createFromParcel(Parcel source) {
+ return new Road(source);
+ }
+
+ @Override
+ public Road[] newArray(int size) {
+ return new Road[size];
+ }
+ };
+
+ @SuppressWarnings("unchecked")
+ private Road(Parcel in) {
+ status = in.readInt();
+ length = in.readDouble();
+ duration = in.readDouble();
+
+ nodes = in.readArrayList(RoadNode.class.getClassLoader());
+ legs = in.readArrayList(RoadLeg.class.getClassLoader());
+ routeHigh = in.readArrayList(GeoPoint.class.getClassLoader());
+ boundingBox = in.readParcelable(BoundingBox.class.getClassLoader());
+ }
+}
diff --git a/VectorTileMap/src/org/osmdroid/routing/RoadLeg.java b/TileMapApp/src/org/osmdroid/routing/RoadLeg.java
similarity index 95%
rename from VectorTileMap/src/org/osmdroid/routing/RoadLeg.java
rename to TileMapApp/src/org/osmdroid/routing/RoadLeg.java
index 1326ab0..a3ec66c 100644
--- a/VectorTileMap/src/org/osmdroid/routing/RoadLeg.java
+++ b/TileMapApp/src/org/osmdroid/routing/RoadLeg.java
@@ -1,78 +1,77 @@
-package org.osmdroid.routing;
-
-import java.util.ArrayList;
-
-import org.osmdroid.utils.BonusPackHelper;
-
-import android.os.Parcel;
-import android.os.Parcelable;
-import android.util.Log;
-
-/**
- * Road Leg is the portion of the road between 2 waypoints (intermediate points
- * requested)
- *
- * @author M.Kergall
- */
-public class RoadLeg implements Parcelable {
- /** 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 RoadLeg() {
- length = duration = 0.0;
- startNodeIndex = endNodeIndex = 0;
- }
-
- public RoadLeg(int startNodeIndex, int endNodeIndex,
- ArrayList nodes) {
- this.startNodeIndex = startNodeIndex;
- this.endNodeIndex = endNodeIndex;
- length = duration = 0.0;
-
- for (int i = startNodeIndex; i <= endNodeIndex; i++) {
- RoadNode node = nodes.get(i);
- length += node.length;
- duration += node.duration;
- }
- Log.d(BonusPackHelper.LOG_TAG, "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 CREATOR = new Parcelable.Creator() {
- @Override
- public RoadLeg createFromParcel(Parcel in) {
- RoadLeg rl = new RoadLeg();
- rl.length = in.readDouble();
- rl.duration = in.readDouble();
- rl.startNodeIndex = in.readInt();
- rl.endNodeIndex = in.readInt();
- return rl;
- }
-
- @Override
- public RoadLeg[] newArray(int size) {
- return new RoadLeg[size];
- }
- };
-}
+package org.osmdroid.routing;
+
+import java.util.ArrayList;
+
+import org.osmdroid.utils.BonusPackHelper;
+
+import android.os.Parcel;
+import android.os.Parcelable;
+import android.util.Log;
+
+/**
+ * Road Leg is the portion of the road between 2 waypoints (intermediate points
+ * requested)
+ * @author M.Kergall
+ */
+public class RoadLeg implements Parcelable {
+ /** 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 RoadLeg() {
+ length = duration = 0.0;
+ startNodeIndex = endNodeIndex = 0;
+ }
+
+ public RoadLeg(int startNodeIndex, int endNodeIndex,
+ ArrayList nodes) {
+ this.startNodeIndex = startNodeIndex;
+ this.endNodeIndex = endNodeIndex;
+ length = duration = 0.0;
+
+ for (int i = startNodeIndex; i <= endNodeIndex; i++) {
+ RoadNode node = nodes.get(i);
+ length += node.length;
+ duration += node.duration;
+ }
+ Log.d(BonusPackHelper.LOG_TAG, "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 CREATOR = new Parcelable.Creator() {
+ @Override
+ public RoadLeg createFromParcel(Parcel in) {
+ RoadLeg rl = new RoadLeg();
+ rl.length = in.readDouble();
+ rl.duration = in.readDouble();
+ rl.startNodeIndex = in.readInt();
+ rl.endNodeIndex = in.readInt();
+ return rl;
+ }
+
+ @Override
+ public RoadLeg[] newArray(int size) {
+ return new RoadLeg[size];
+ }
+ };
+}
diff --git a/VectorTileMap/src/org/osmdroid/routing/RoadManager.java b/TileMapApp/src/org/osmdroid/routing/RoadManager.java
similarity index 86%
rename from VectorTileMap/src/org/osmdroid/routing/RoadManager.java
rename to TileMapApp/src/org/osmdroid/routing/RoadManager.java
index b0606a1..d6f0265 100644
--- a/VectorTileMap/src/org/osmdroid/routing/RoadManager.java
+++ b/TileMapApp/src/org/osmdroid/routing/RoadManager.java
@@ -1,84 +1,83 @@
-package org.osmdroid.routing;
-
-import java.util.ArrayList;
-
-import org.oscim.core.GeoPoint;
-import org.oscim.overlay.PathOverlay;
-import org.oscim.view.MapView;
-
-import android.content.Context;
-import android.graphics.Paint;
-
-/**
- * Generic class to get a route between a start and a destination point, going
- * through a list of waypoints.
- *
- * @see MapQuestRoadManager
- * @see GoogleRoadManager
- * @see OSRMRoadManager
- * @author M.Kergall
- */
-public abstract class RoadManager {
-
- protected String mOptions;
-
- public abstract Road getRoad(ArrayList waypoints);
-
- public RoadManager() {
- 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();
- }
-
- public static PathOverlay buildRoadOverlay(MapView mapView, Road road, Paint paint,
- Context context) {
- PathOverlay roadOverlay = new PathOverlay(mapView, 0, context);
- roadOverlay.setPaint(paint);
- if (road != null) {
- ArrayList polyline = road.routeHigh;
- for (GeoPoint p : polyline) {
- roadOverlay.addPoint(p);
- }
- }
- return roadOverlay;
- }
-
- /**
- * Builds an overlay for the road shape with a default (and nice!) color.
- *
- * @param mapView
- * ..
- * @param road
- * ..
- * @param context
- * ..
- * @return route shape overlay
- */
- public static PathOverlay buildRoadOverlay(MapView mapView, Road road, Context context) {
- Paint paint = new Paint();
- paint.setColor(0x800000FF);
- paint.setStyle(Paint.Style.STROKE);
- paint.setStrokeWidth(5);
- return buildRoadOverlay(mapView, road, paint, context);
- }
-
-}
+package org.osmdroid.routing;
+
+import java.util.ArrayList;
+
+import org.oscim.core.GeoPoint;
+import org.oscim.overlay.PathOverlay;
+import org.oscim.view.MapView;
+import org.osmdroid.routing.provider.GoogleRoadManager;
+import org.osmdroid.routing.provider.MapQuestRoadManager;
+import org.osmdroid.routing.provider.OSRMRoadManager;
+
+import android.content.Context;
+import android.graphics.Paint;
+
+/**
+ * Generic class to get a route between a start and a destination point, going
+ * through a list of waypoints.
+ * @see MapQuestRoadManager
+ * @see GoogleRoadManager
+ * @see OSRMRoadManager
+ * @author M.Kergall
+ */
+public abstract class RoadManager {
+
+ protected String mOptions;
+
+ public abstract Road getRoad(ArrayList waypoints);
+
+ public RoadManager() {
+ 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();
+ }
+
+ public static PathOverlay buildRoadOverlay(MapView mapView, Road road, Paint paint) {
+ PathOverlay roadOverlay = new PathOverlay(mapView, 0);
+ roadOverlay.setPaint(paint);
+ if (road != null) {
+ ArrayList polyline = road.routeHigh;
+ for (GeoPoint p : polyline) {
+ roadOverlay.addPoint(p);
+ }
+ }
+ return roadOverlay;
+ }
+
+ /**
+ * Builds an overlay for the road shape with a default (and nice!) color.
+ * @param mapView
+ * ..
+ * @param road
+ * ..
+ * @param context
+ * ..
+ * @return route shape overlay
+ */
+ public static PathOverlay buildRoadOverlay(MapView mapView, Road road) {
+ Paint paint = new Paint();
+ paint.setColor(0x800000FF);
+ paint.setStyle(Paint.Style.STROKE);
+ paint.setStrokeWidth(5);
+ return buildRoadOverlay(mapView, road, paint);
+ }
+
+}
diff --git a/VectorTileMap/src/org/osmdroid/routing/RoadNode.java b/TileMapApp/src/org/osmdroid/routing/RoadNode.java
similarity index 95%
rename from VectorTileMap/src/org/osmdroid/routing/RoadNode.java
rename to TileMapApp/src/org/osmdroid/routing/RoadNode.java
index a6645dc..3a8256e 100644
--- a/VectorTileMap/src/org/osmdroid/routing/RoadNode.java
+++ b/TileMapApp/src/org/osmdroid/routing/RoadNode.java
@@ -1,72 +1,71 @@
-package org.osmdroid.routing;
-
-import org.oscim.core.GeoPoint;
-
-import android.os.Parcel;
-import android.os.Parcelable;
-
-/**
- * Road intersection, with instructions to continue.
- *
- * @author M.Kergall
- */
-public class RoadNode implements Parcelable {
- /**
- * @see Maneuver
- * Types
- */
- public int maneuverType;
- /** textual information on what to do at this intersection */
- public String instructions;
- /** index in road links array - internal use only, for MapQuest directions */
- public int nextRoadLink;
- /** 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 RoadNode() {
- maneuverType = 0;
- nextRoadLink = -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 CREATOR = new
- Parcelable.Creator() {
- @Override
- public RoadNode createFromParcel(Parcel in) {
- RoadNode rn = new RoadNode();
- 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 RoadNode[] newArray(int size) {
- return new RoadNode[size];
- }
- };
-
-}
+package org.osmdroid.routing;
+
+import org.oscim.core.GeoPoint;
+
+import android.os.Parcel;
+import android.os.Parcelable;
+
+/**
+ * Road intersection, with instructions to continue.
+ * @author M.Kergall
+ */
+public class RoadNode implements Parcelable {
+ /**
+ * @see Maneuver
+ * Types
+ */
+ public int maneuverType;
+ /** textual information on what to do at this intersection */
+ public String instructions;
+ /** index in road links array - internal use only, for MapQuest directions */
+ public int nextRoadLink;
+ /** 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 RoadNode() {
+ maneuverType = 0;
+ nextRoadLink = -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 CREATOR = new
+ Parcelable.Creator() {
+ @Override
+ public RoadNode createFromParcel(Parcel in) {
+ RoadNode rn = new RoadNode();
+ 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 RoadNode[] newArray(int size) {
+ return new RoadNode[size];
+ }
+ };
+
+}
diff --git a/VectorTileMap/src/org/osmdroid/routing/GoogleRoadManager.java b/TileMapApp/src/org/osmdroid/routing/provider/GoogleRoadManager.java
similarity index 96%
rename from VectorTileMap/src/org/osmdroid/routing/GoogleRoadManager.java
rename to TileMapApp/src/org/osmdroid/routing/provider/GoogleRoadManager.java
index d00cc96..924f3b2 100644
--- a/VectorTileMap/src/org/osmdroid/routing/GoogleRoadManager.java
+++ b/TileMapApp/src/org/osmdroid/routing/provider/GoogleRoadManager.java
@@ -1,230 +1,232 @@
-package org.osmdroid.routing;
-
-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;
-
-import org.oscim.core.BoundingBox;
-import org.oscim.core.GeoPoint;
-import org.osmdroid.utils.BonusPackHelper;
-import org.osmdroid.utils.HttpConnection;
-import org.osmdroid.utils.PolylineEncoder;
-import org.xml.sax.Attributes;
-import org.xml.sax.SAXException;
-import org.xml.sax.helpers.DefaultHandler;
-
-import android.util.Log;
-
-/**
- * class to get a route between a start and a destination point, going through a
- * list of waypoints.
- * https://developers.google.com/maps/documentation/directions/
- * 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 GoogleRoadManager extends RoadManager {
-
- 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(ArrayList 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 road
- */
- @Override
- public Road getRoad(ArrayList waypoints) {
- String url = getUrl(waypoints);
- Log.d(BonusPackHelper.LOG_TAG, "GoogleRoadManager.getRoad:" + url);
- Road road = null;
- HttpConnection connection = new HttpConnection();
- connection.doGet(url);
- InputStream stream = connection.getStream();
- if (stream != null)
- road = getRoadXML(stream);
- connection.close();
- if (road == null || road.routeHigh.size() == 0) {
- //Create default road:
- road = new Road(waypoints);
- } else {
- //finalize road data update:
- for (RoadLeg leg : road.legs) {
- road.duration += leg.duration;
- road.length += leg.length;
- }
- road.status = Road.STATUS_OK;
- }
- Log.d(BonusPackHelper.LOG_TAG, "GoogleRoadManager.getRoad - finished");
- return road;
- }
-
- protected Road getRoadXML(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.mRoad;
- }
-
-}
-
-class GoogleDirectionsHandler extends DefaultHandler {
- Road mRoad;
- RoadLeg mLeg;
- RoadNode 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;
- mRoad = new Road();
- }
-
- @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 RoadLeg();
- isLeg = true;
- } else if (localName.equals("step")) {
- mNode = new RoadNode();
- 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 road for the step, to add:
- ArrayList polyLine = PolylineEncoder.decode(mString, 10);
- mRoad.routeHigh.addAll(polyLine);
- } else if (isOverviewPolyline) {
- //low-def polyline for the whole road:
- mRoad.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(" ", " ");
- mNode.instructions = mString;
- //Log.d(BonusPackHelper.LOG_TAG, mString);
- }
- } else if (localName.equals("start_location")) {
- if (isStep)
- mNode.location = new GeoPoint(mLat, mLng);
- } else if (localName.equals("step")) {
- mRoad.nodes.add(mNode);
- isStep = false;
- } else if (localName.equals("leg")) {
- mRoad.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")) {
- mRoad.boundingBox = new BoundingBox(mNorth, mEast, mSouth, mWest);
- isBB = false;
- }
- }
-
-}
+package org.osmdroid.routing.provider;
+
+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;
+
+import org.oscim.core.BoundingBox;
+import org.oscim.core.GeoPoint;
+import org.osmdroid.routing.Road;
+import org.osmdroid.routing.RoadLeg;
+import org.osmdroid.routing.RoadManager;
+import org.osmdroid.routing.RoadNode;
+import org.osmdroid.utils.BonusPackHelper;
+import org.osmdroid.utils.HttpConnection;
+import org.osmdroid.utils.PolylineEncoder;
+import org.xml.sax.Attributes;
+import org.xml.sax.SAXException;
+import org.xml.sax.helpers.DefaultHandler;
+
+import android.util.Log;
+
+/**
+ * class to get a route between a start and a destination point, going through a
+ * list of waypoints.
+ * https://developers.google.com/maps/documentation/directions/
+ * 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 GoogleRoadManager extends RoadManager {
+
+ 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(ArrayList 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 road
+ */
+ @Override
+ public Road getRoad(ArrayList waypoints) {
+ String url = getUrl(waypoints);
+ Log.d(BonusPackHelper.LOG_TAG, "GoogleRoadManager.getRoad:" + url);
+ Road road = null;
+ HttpConnection connection = new HttpConnection();
+ connection.doGet(url);
+ InputStream stream = connection.getStream();
+ if (stream != null)
+ road = getRoadXML(stream);
+ connection.close();
+ if (road == null || road.routeHigh.size() == 0) {
+ //Create default road:
+ road = new Road(waypoints);
+ } else {
+ //finalize road data update:
+ for (RoadLeg leg : road.legs) {
+ road.duration += leg.duration;
+ road.length += leg.length;
+ }
+ road.status = Road.STATUS_OK;
+ }
+ Log.d(BonusPackHelper.LOG_TAG, "GoogleRoadManager.getRoad - finished");
+ return road;
+ }
+
+ protected Road getRoadXML(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.mRoad;
+ }
+
+}
+
+class GoogleDirectionsHandler extends DefaultHandler {
+ Road mRoad;
+ RoadLeg mLeg;
+ RoadNode 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;
+ mRoad = new Road();
+ }
+
+ @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 RoadLeg();
+ isLeg = true;
+ } else if (localName.equals("step")) {
+ mNode = new RoadNode();
+ 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 road for the step, to add:
+ ArrayList polyLine = PolylineEncoder.decode(mString, 10);
+ mRoad.routeHigh.addAll(polyLine);
+ } else if (isOverviewPolyline) {
+ //low-def polyline for the whole road:
+ mRoad.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(" ", " ");
+ mNode.instructions = mString;
+ //Log.d(BonusPackHelper.LOG_TAG, mString);
+ }
+ } else if (localName.equals("start_location")) {
+ if (isStep)
+ mNode.location = new GeoPoint(mLat, mLng);
+ } else if (localName.equals("step")) {
+ mRoad.nodes.add(mNode);
+ isStep = false;
+ } else if (localName.equals("leg")) {
+ mRoad.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")) {
+ mRoad.boundingBox = new BoundingBox(mNorth, mEast, mSouth, mWest);
+ isBB = false;
+ }
+ }
+
+}
diff --git a/VectorTileMap/src/org/osmdroid/routing/MapQuestRoadManager.java b/TileMapApp/src/org/osmdroid/routing/provider/MapQuestRoadManager.java
similarity index 96%
rename from VectorTileMap/src/org/osmdroid/routing/MapQuestRoadManager.java
rename to TileMapApp/src/org/osmdroid/routing/provider/MapQuestRoadManager.java
index da6bf64..e536275 100644
--- a/VectorTileMap/src/org/osmdroid/routing/MapQuestRoadManager.java
+++ b/TileMapApp/src/org/osmdroid/routing/provider/MapQuestRoadManager.java
@@ -1,278 +1,278 @@
-package org.osmdroid.routing;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.ArrayList;
-
-import javax.xml.parsers.ParserConfigurationException;
-import javax.xml.parsers.SAXParser;
-import javax.xml.parsers.SAXParserFactory;
-
-import org.oscim.core.BoundingBox;
-import org.oscim.core.GeoPoint;
-import org.osmdroid.utils.BonusPackHelper;
-import org.osmdroid.utils.HttpConnection;
-import org.osmdroid.utils.PolylineEncoder;
-import org.xml.sax.Attributes;
-import org.xml.sax.SAXException;
-import org.xml.sax.helpers.DefaultHandler;
-
-import android.util.Log;
-
-/**
- * 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.
- * See http://open.mapquestapi.com/guidance
- *
- * @author M.Kergall
- */
-public class MapQuestRoadManager extends RoadManager {
-
- 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(ArrayList 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 road
- */
- @Override
- public Road getRoad(ArrayList waypoints) {
- String url = getUrl(waypoints);
- Log.d(BonusPackHelper.LOG_TAG, "MapQuestRoadManager.getRoute:" + url);
- Road road = null;
- HttpConnection connection = new HttpConnection();
- connection.doGet(url);
- InputStream stream = connection.getStream();
- if (stream != null)
- road = getRoadXML(stream, waypoints);
- if (road == null || road.routeHigh.size() == 0) {
- // Create default road:
- road = new Road(waypoints);
- }
- connection.close();
- Log.d(BonusPackHelper.LOG_TAG, "MapQuestRoadManager.getRoute - finished");
- return road;
- }
-
- /**
- * XML implementation
- *
- * @param is
- * : input stream to parse
- * @param waypoints
- * ...
- * @return the road ...
- */
- protected Road getRoadXML(InputStream is, ArrayList 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();
- }
- Road road = handler.mRoad;
- if (road != null && road.routeHigh.size() > 0) {
- road.nodes = finalizeNodes(road.nodes, handler.mLinks, road.routeHigh);
- road.buildLegs(waypoints);
- road.status = Road.STATUS_OK;
- }
- return road;
- }
-
- protected ArrayList finalizeNodes(ArrayList mNodes,
- ArrayList mLinks, ArrayList polyline) {
- int n = mNodes.size();
- if (n == 0)
- return mNodes;
- ArrayList newNodes = new ArrayList(n);
- RoadNode lastNode = null;
- for (int i = 1; i < n - 1; i++) { // 1, n-1 => first and last MapQuest
- // nodes are irrelevant.
- RoadNode node = mNodes.get(i);
- RoadLink link = mLinks.get(node.nextRoadLink);
- 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;
- }
-}
-
-/** Road Link is a portion of road between 2 "nodes" or intersections */
-class RoadLink {
- /** 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 Road mRoad;
- public ArrayList mLinks;
-
- boolean isBB;
- boolean isGuidanceNodeCollection;
- private String mString;
- double mLat, mLng;
- double mNorth, mWest, mSouth, mEast;
- RoadLink mLink;
- RoadNode mNode;
-
- public XMLHandler() {
- isBB = isGuidanceNodeCollection = false;
- mRoad = new Road();
- mLinks = new ArrayList();
- }
-
- @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 RoadLink();
- else if (localName.equals("node"))
- mNode = new RoadNode();
- 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")) {
- mRoad.routeHigh = PolylineEncoder.decode(mString, 10);
- // Log.d("DD", "High="+mRoad.mRouteHigh.size());
- } else if (localName.equals("generalizedShape")) {
- mRoad.setRouteLow(PolylineEncoder.decode(mString, 10));
- // Log.d("DD", "Low="+mRoad.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 road 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);
- mRoad.length += mLink.mLength;
- mRoad.duration += mLink.mDuration;
- mLink = null;
- } else if (localName.equals("turnCost")) {
- int turnCost = Integer.parseInt(mString);
- mNode.duration += turnCost;
- mRoad.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.nextRoadLink = Integer.parseInt(mString);
- } else if (localName.equals("node")) {
- mRoad.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")) {
- mRoad.boundingBox = new BoundingBox(mNorth, mEast, mSouth, mWest);
- isBB = false;
- }
- }
-}
+package org.osmdroid.routing.provider;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.ArrayList;
+
+import javax.xml.parsers.ParserConfigurationException;
+import javax.xml.parsers.SAXParser;
+import javax.xml.parsers.SAXParserFactory;
+
+import org.oscim.core.BoundingBox;
+import org.oscim.core.GeoPoint;
+import org.osmdroid.routing.Road;
+import org.osmdroid.routing.RoadManager;
+import org.osmdroid.routing.RoadNode;
+import org.osmdroid.utils.BonusPackHelper;
+import org.osmdroid.utils.HttpConnection;
+import org.osmdroid.utils.PolylineEncoder;
+import org.xml.sax.Attributes;
+import org.xml.sax.SAXException;
+import org.xml.sax.helpers.DefaultHandler;
+
+import android.util.Log;
+
+/**
+ * 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.
+ * See http://open.mapquestapi.com/guidance
+ * @author M.Kergall
+ */
+public class MapQuestRoadManager extends RoadManager {
+
+ 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(ArrayList 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 road
+ */
+ @Override
+ public Road getRoad(ArrayList waypoints) {
+ String url = getUrl(waypoints);
+ Log.d(BonusPackHelper.LOG_TAG, "MapQuestRoadManager.getRoute:" + url);
+ Road road = null;
+ HttpConnection connection = new HttpConnection();
+ connection.doGet(url);
+ InputStream stream = connection.getStream();
+ if (stream != null)
+ road = getRoadXML(stream, waypoints);
+ if (road == null || road.routeHigh.size() == 0) {
+ // Create default road:
+ road = new Road(waypoints);
+ }
+ connection.close();
+ Log.d(BonusPackHelper.LOG_TAG, "MapQuestRoadManager.getRoute - finished");
+ return road;
+ }
+
+ /**
+ * XML implementation
+ * @param is
+ * : input stream to parse
+ * @param waypoints
+ * ...
+ * @return the road ...
+ */
+ protected Road getRoadXML(InputStream is, ArrayList 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();
+ }
+ Road road = handler.mRoad;
+ if (road != null && road.routeHigh.size() > 0) {
+ road.nodes = finalizeNodes(road.nodes, handler.mLinks, road.routeHigh);
+ road.buildLegs(waypoints);
+ road.status = Road.STATUS_OK;
+ }
+ return road;
+ }
+
+ protected ArrayList finalizeNodes(ArrayList mNodes,
+ ArrayList mLinks, ArrayList polyline) {
+ int n = mNodes.size();
+ if (n == 0)
+ return mNodes;
+ ArrayList newNodes = new ArrayList(n);
+ RoadNode lastNode = null;
+ for (int i = 1; i < n - 1; i++) { // 1, n-1 => first and last MapQuest
+ // nodes are irrelevant.
+ RoadNode node = mNodes.get(i);
+ RoadLink link = mLinks.get(node.nextRoadLink);
+ 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;
+ }
+}
+
+/** Road Link is a portion of road between 2 "nodes" or intersections */
+class RoadLink {
+ /** 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 Road mRoad;
+ public ArrayList mLinks;
+
+ boolean isBB;
+ boolean isGuidanceNodeCollection;
+ private String mString;
+ double mLat, mLng;
+ double mNorth, mWest, mSouth, mEast;
+ RoadLink mLink;
+ RoadNode mNode;
+
+ public XMLHandler() {
+ isBB = isGuidanceNodeCollection = false;
+ mRoad = new Road();
+ mLinks = new ArrayList();
+ }
+
+ @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 RoadLink();
+ else if (localName.equals("node"))
+ mNode = new RoadNode();
+ 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")) {
+ mRoad.routeHigh = PolylineEncoder.decode(mString, 10);
+ // Log.d("DD", "High="+mRoad.mRouteHigh.size());
+ } else if (localName.equals("generalizedShape")) {
+ mRoad.setRouteLow(PolylineEncoder.decode(mString, 10));
+ // Log.d("DD", "Low="+mRoad.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 road 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);
+ mRoad.length += mLink.mLength;
+ mRoad.duration += mLink.mDuration;
+ mLink = null;
+ } else if (localName.equals("turnCost")) {
+ int turnCost = Integer.parseInt(mString);
+ mNode.duration += turnCost;
+ mRoad.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.nextRoadLink = Integer.parseInt(mString);
+ } else if (localName.equals("node")) {
+ mRoad.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")) {
+ mRoad.boundingBox = new BoundingBox(mNorth, mEast, mSouth, mWest);
+ isBB = false;
+ }
+ }
+}
diff --git a/VectorTileMap/src/org/osmdroid/routing/OSRMRoadManager.java b/TileMapApp/src/org/osmdroid/routing/provider/OSRMRoadManager.java
similarity index 97%
rename from VectorTileMap/src/org/osmdroid/routing/OSRMRoadManager.java
rename to TileMapApp/src/org/osmdroid/routing/provider/OSRMRoadManager.java
index c1d91c1..830ecde 100644
--- a/VectorTileMap/src/org/osmdroid/routing/OSRMRoadManager.java
+++ b/TileMapApp/src/org/osmdroid/routing/provider/OSRMRoadManager.java
@@ -1,278 +1,281 @@
-package org.osmdroid.routing;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Locale;
-
-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.osmdroid.utils.PolylineEncoder;
-
-import android.util.Log;
-
-/**
- * get a route between a start and a destination point. It uses OSRM, a free
- * open source routing service based on OpenSteetMap data.
- * See https://github.com/DennisOSRM/Project-OSRM/wiki/Server-api
- * It requests by default the OSRM demo site. Use setService() to request an
- * other (for instance your own) OSRM service.
- * TODO: improve internationalization of instructions
- * @author M.Kergall
- */
-public class OSRMRoadManager extends RoadManager {
-
- 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 MANEUVERS;
- static {
- MANEUVERS = new HashMap();
- 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: road name
- // %d: direction => removed
- // <*>: will only be printed when there actually is a road name
- static final HashMap> DIRECTIONS;
- static {
- DIRECTIONS = new HashMap>();
- HashMap directions;
-
- directions = new HashMap();
- 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", "");
- 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();
- 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", "");
- 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();
- DIRECTIONS.put("pl", directions);
- directions.put("0", "Nieznana instrukcja");
- directions.put("1", "Kontynuuj jazdę");
- directions.put("2", "Skręć lekko w prawo");
- directions.put("3", "Skręć w prawo");
- directions.put("4", "Skręć ostro w prawo");
- directions.put("5", "Zawróć");
- directions.put("6", "Skręć ostro w lewo");
- directions.put("7", "Skręć w lewo");
- directions.put("8", "Skręć lekko w lewo");
- directions.put("9", "Dotarłeś do punktu pośredniego");
- directions.put("10", "");
- directions.put("11-1", "Wjedź na rondo i opuść je pierwszym zjazdem");
- directions.put("11-2", "Wjedź na rondo i opuść je drugim zjazdem");
- directions.put("11-3", "Wjedź na rondo i opuść je trzecim zjazdem");
- directions.put("11-4", "Wjedź na rondo i opuść je czwartym zjazdem");
- directions.put("11-5", "Wjedź na rondo i opuść je piątym zjazdem");
- directions.put("11-6", "Wjedź na rondo i opuść je szóstym zjazdem");
- directions.put("11-7", "Wjedź na rondo i opuść je siódmym zjazdem");
- directions.put("11-8", "Wjedź na rondo i opuść je ósmym zjazdem");
- directions.put("11-9", "Wjedź na rondo i opuść je dziewiątym zjazdem");
- directions.put("15", "Dotarłeś do celu podróży");
- }
-
- public OSRMRoadManager() {
- 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(ArrayList 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 Road getRoad(ArrayList waypoints) {
- String url = getUrl(waypoints);
- Log.d(BonusPackHelper.LOG_TAG, "OSRMRoadManager.getRoad:" + 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.e(BonusPackHelper.LOG_TAG, "OSRMRoadManager::getRoad: request failed.");
- return new Road(waypoints);
- }
- Locale l = Locale.getDefault();
- HashMap