/walkytalky/src/com/googlecode/eyesfree/walkytalky/StreetLocator.java

http://eyes-free.googlecode.com/ · Java · 421 lines · 237 code · 31 blank · 153 comment · 21 complexity · 32a007001f2cd18ccbcfdb5f750b372c MD5 · raw file

  1. /*
  2. * Copyright (C) 2008 Google Inc.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License"); you may not
  5. * use this file except in compliance with the License. You may obtain a copy of
  6. * the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  12. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  13. * License for the specific language governing permissions and limitations under
  14. * the License.
  15. */
  16. package com.googlecode.eyesfree.walkytalky;
  17. import org.json.JSONException;
  18. import org.json.JSONObject;
  19. import android.location.Location;
  20. import android.location.LocationManager;
  21. import java.io.BufferedReader;
  22. import java.io.IOException;
  23. import java.io.InputStream;
  24. import java.io.InputStreamReader;
  25. import java.net.HttpURLConnection;
  26. import java.net.MalformedURLException;
  27. import java.net.URL;
  28. import java.util.HashSet;
  29. /**
  30. * This class implements methods to get street address from lat-lon using
  31. * reverse geocoding API through HTTP.
  32. *
  33. * @author chaitanyag@google.com (Chaitanya Gharpure)
  34. */
  35. public class StreetLocator {
  36. /**
  37. * Interface for the callbacks to be used when a street is located
  38. */
  39. public interface StreetLocatorListener {
  40. public void onIntersectionLocated(String[] streetnames);
  41. public void onAddressLocated(Address address);
  42. public void onFrontBackLocated(String[] streetsFront, String[] streetsBack);
  43. }
  44. private StreetLocatorListener cb;
  45. private static final String ENCODING = "UTF-8";
  46. // URL for obtaining navigation directions
  47. private static final String URL_NAV_STRING = "http://maps.google.com/maps/nav?";
  48. // URL for obtaining reverse geocoded location
  49. private static final String URL_GEO_STRING = "http://maps.google.com/maps/api/geocode/json?sensor=false&latlng=";
  50. public StreetLocator(StreetLocatorListener callback) {
  51. cb = callback;
  52. }
  53. /**
  54. * Queries the map server and obtains the street names at the specified
  55. * location. This is done by obtaining street name at specified location,
  56. * and at locations X meters to the N, S, E, and W of the specified
  57. * location.
  58. *
  59. * @param lat The latitude in degrees
  60. * @param lon The longitude in degrees
  61. */
  62. public void getStreetIntersectionAsync(double lat, double lon) {
  63. final double latitude = lat;
  64. final double longitude = lon;
  65. /**
  66. * Runnable for fetching the address asynchronously
  67. */
  68. class IntersectionThread implements Runnable {
  69. public void run() {
  70. cb.onIntersectionLocated(getStreetIntersection(latitude, longitude));
  71. }
  72. }
  73. (new Thread(new IntersectionThread())).start();
  74. }
  75. /**
  76. * Queries the map server and obtains the street names at the specified
  77. * location. This is done by obtaining street name at specified location,
  78. * and at locations X meters to the N, S, E, and W of the specified
  79. * location.
  80. *
  81. * @param lat The latitude in degrees
  82. * @param lon The longitude in degrees
  83. */
  84. public void getStreetsInFrontAndBackAsync(double lat, double lon, double heading) {
  85. final double latitude = lat;
  86. final double longitude = lon;
  87. final double direction = heading;
  88. /**
  89. * Runnable for fetching the front and back streets asynchronously
  90. */
  91. class FrontBackStreetsThread implements Runnable {
  92. public void run() {
  93. getStreetsInFrontAndBack(latitude, longitude, direction);
  94. }
  95. }
  96. (new Thread(new FrontBackStreetsThread())).start();
  97. }
  98. /**
  99. * Queries the map server and obtains the reverse geocoded address of the
  100. * specified location.
  101. *
  102. * @param lat The latitude in degrees
  103. * @param lon The longitude in degrees
  104. */
  105. public void getAddressAsync(double lat, double lon) {
  106. final double latitude = lat;
  107. final double longitude = lon;
  108. /**
  109. * Runnable for fetching the address asynchronously
  110. */
  111. class AddressThread implements Runnable {
  112. public void run() {
  113. cb.onAddressLocated(getAddress(latitude, longitude));
  114. }
  115. }
  116. (new Thread(new AddressThread())).start();
  117. }
  118. /**
  119. * Queries the map server and obtains the street names at the specified
  120. * location. This is done by obtaining street name at specified location,
  121. * and at locations X meters to the N, S, E, and W of the specified
  122. * location.
  123. *
  124. * @param lat The latitude in degrees
  125. * @param lon The longitude in degrees
  126. * @return Returns the string array containing street names
  127. */
  128. public String[] getStreetIntersection(double lat, double lon) {
  129. HashSet<String> streets = new HashSet<String>();
  130. try {
  131. for (int i = 0; i < 5; i++) {
  132. // Find street address at lat-lon x meters to the N, S, E and W
  133. // of
  134. // the given lat-lon
  135. String street = parseStreetName(getResult(makeNavURL(lat, lon, lat, lon)));
  136. if (street != null) {
  137. streets.add(street);
  138. }
  139. // get points 150m away, towards N, E, S, and W
  140. if (i < 4) {
  141. Location nextLoc = endLocation(lat, lon, i * 90, 15);
  142. lat = nextLoc.getLatitude();
  143. lon = nextLoc.getLongitude();
  144. }
  145. }
  146. } catch (MalformedURLException mue) {
  147. } catch (IOException e) {
  148. } catch (JSONException e) {
  149. }
  150. String[] st = new String[streets.size()];
  151. int i = 0;
  152. for (String s : streets) {
  153. st[i++] = s;
  154. }
  155. return st;
  156. }
  157. /**
  158. * Queries the map server and obtains the street names at the specified
  159. * location. This is done by obtaining street name at specified location,
  160. * and at locations X meters to the N, S, E, and W of the specified
  161. * location.
  162. *
  163. * @param lat The latitude in degrees
  164. * @param lon The longitude in degrees
  165. */
  166. public void getStreetsInFrontAndBack(double lat, double lon, double heading) {
  167. HashSet<String> streetsFront = new HashSet<String>();
  168. HashSet<String> streetsBack = new HashSet<String>();
  169. double searchDistance = 15; // 15m (? - is there really a factor of 10
  170. // here)
  171. try {
  172. // Get the current street
  173. String street = parseStreetName(getResult(makeNavURL(lat, lon, lat, lon)));
  174. if (street != null) {
  175. streetsFront.add(street);
  176. streetsBack.add(street);
  177. }
  178. // Get the street in front of the current street
  179. Location nextLoc = endLocation(lat, lon, heading, searchDistance);
  180. lat = nextLoc.getLatitude();
  181. lon = nextLoc.getLongitude();
  182. street = parseStreetName(getResult(makeNavURL(lat, lon, lat, lon)));
  183. if (street != null) {
  184. streetsFront.add(street);
  185. }
  186. // Get the street behind the current street
  187. heading = heading + 180;
  188. if (heading >= 360) {
  189. heading = heading - 360;
  190. }
  191. nextLoc = endLocation(lat, lon, heading, searchDistance);
  192. lat = nextLoc.getLatitude();
  193. lon = nextLoc.getLongitude();
  194. street = parseStreetName(getResult(makeNavURL(lat, lon, lat, lon)));
  195. if (street != null) {
  196. streetsBack.add(street);
  197. }
  198. String[] sf = new String[streetsFront.size()];
  199. int i = 0;
  200. for (String s : streetsFront) {
  201. sf[i++] = s;
  202. }
  203. String[] sb = new String[streetsBack.size()];
  204. i = 0;
  205. for (String s : streetsBack) {
  206. sb[i++] = s;
  207. }
  208. cb.onFrontBackLocated(sf, sb);
  209. } catch (MalformedURLException e) {
  210. e.printStackTrace();
  211. } catch (JSONException e) {
  212. e.printStackTrace();
  213. } catch (IOException e) {
  214. e.printStackTrace();
  215. }
  216. }
  217. /**
  218. * Queries the map server and obtains the reverse geocoded address of the
  219. * specified location.
  220. *
  221. * @param lat The latitude in degrees
  222. * @param lon The longitude in degrees
  223. * @return Returns the reverse geocoded address
  224. */
  225. public Address getAddress(double lat, double lon) {
  226. try {
  227. String resp = getResult(makeGeoURL(lat, lon));
  228. return new Address(resp);
  229. } catch (MalformedURLException mue) {
  230. } catch (IOException e) {
  231. }
  232. return null;
  233. }
  234. /**
  235. * Parses the JSON response to extract the street name.
  236. *
  237. * @param resp The String representation of the JSON response
  238. * @return Returns the street name
  239. * @throws JSONException
  240. */
  241. private String parseStreetName(String resp) throws JSONException {
  242. JSONObject jsonObj = new JSONObject(resp);
  243. int code = jsonObj.getJSONObject("Status").getInt("code");
  244. if (code == 200) {
  245. return extendShorts(jsonObj.getJSONArray("Placemark").getJSONObject(0).getString(
  246. "address"));
  247. }
  248. return null;
  249. }
  250. /**
  251. * Sends a request to the specified URL and obtains the result from the
  252. * sever.
  253. *
  254. * @param url The URL to connect to
  255. * @return the server response
  256. * @throws IOException
  257. */
  258. private String getResult(URL url) throws IOException {
  259. HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  260. conn.setDoInput(true);
  261. conn.setDoOutput(true);
  262. InputStream is = conn.getInputStream();
  263. String result = toString(is);
  264. return result;
  265. }
  266. /**
  267. * Prepares the URL to connect to navigation server, from the specified
  268. * start and end location coordinates
  269. *
  270. * @param lat1 Start location latitude in degrees
  271. * @param lon1 Start location longitude in degrees
  272. * @param lat2 End location latitude in degrees
  273. * @param lon2 End location longitude in degrees
  274. * @return a well-formed URL
  275. * @throws MalformedURLException
  276. */
  277. private URL makeNavURL(double lat1, double lon1, double lat2, double lon2)
  278. throws MalformedURLException {
  279. StringBuilder url = new StringBuilder();
  280. url.append(URL_NAV_STRING).append("hl=EN&gl=EN&output=js&oe=utf8&q=from%3A").append(lat1)
  281. .append(",").append(lon1).append("+to%3A").append(lat2).append(",").append(lon2);
  282. return new URL(url.toString());
  283. }
  284. /**
  285. * Prepares the URL to connect to the reverse geocoding server from the
  286. * specified location coordinates.
  287. *
  288. * @param lat latitude in degrees of the location to reverse geocode
  289. * @param lon longitude in degrees of the location to reverse geocode
  290. * @return URL The Geo URL created based on the given lat/lon
  291. * @throws MalformedURLException
  292. */
  293. private URL makeGeoURL(double lat, double lon) throws MalformedURLException {
  294. StringBuilder url = new StringBuilder();
  295. url.append(URL_GEO_STRING).append(lat).append(",").append(lon);
  296. return new URL(url.toString());
  297. }
  298. /**
  299. * Reads an InputStream and returns its contents as a String.
  300. *
  301. * @param inputStream The InputStream to read from.
  302. * @return The contents of the InputStream as a String.
  303. */
  304. private static String toString(InputStream inputStream) throws IOException {
  305. StringBuilder outputBuilder = new StringBuilder();
  306. String string;
  307. if (inputStream != null) {
  308. BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, ENCODING));
  309. while (null != (string = reader.readLine())) {
  310. outputBuilder.append(string).append('\n');
  311. }
  312. }
  313. return outputBuilder.toString();
  314. }
  315. /**
  316. * Replaces the short forms in the address by their longer forms, so that
  317. * TTS speaks the addresses properly
  318. *
  319. * @param addr The address from which to replace short forms
  320. * @return the modified address string
  321. */
  322. public static String extendShorts(String addr) {
  323. addr = addr.replace("St,", "Street");
  324. addr = addr.replace("St.", "Street");
  325. addr = addr.replace("Rd", "Road");
  326. addr = addr.replace("Fwy", "Freeway");
  327. addr = addr.replace("Pkwy", "Parkway");
  328. addr = addr.replace("Blvd", "Boulevard");
  329. addr = addr.replace("Expy", "Expressway");
  330. addr = addr.replace("Ave", "Avenue");
  331. addr = addr.replace("Dr", "Drive");
  332. return addr;
  333. }
  334. /**
  335. * Computes the new location at a particular direction and distance from the
  336. * specified location using the inverse Vincenti formula.
  337. *
  338. * @param lat1 latitude of source location in degrees
  339. * @param lon1 longitude of source location in degrees
  340. * @param brng Direction in degrees wrt source location
  341. * @param dist Distance from the source location
  342. * @return the new location
  343. */
  344. private Location endLocation(double lat1, double lon1, double brng, double dist) {
  345. double a = 6378137, b = 6356752.3142, f = 1 / 298.257223563;
  346. double s = dist;
  347. double alpha1 = Math.toRadians(brng);
  348. double sinAlpha1 = Math.sin(alpha1), cosAlpha1 = Math.cos(alpha1);
  349. double tanU1 = (1 - f) * Math.tan(Math.toRadians(lat1));
  350. double cosU1 = 1 / Math.sqrt((1 + tanU1 * tanU1)), sinU1 = tanU1 * cosU1;
  351. double sigma1 = Math.atan2(tanU1, cosAlpha1);
  352. double sinAlpha = cosU1 * sinAlpha1;
  353. double cosSqAlpha = 1 - sinAlpha * sinAlpha;
  354. double uSq = cosSqAlpha * (a * a - b * b) / (b * b);
  355. double A = 1 + uSq / 16384 * (4096 + uSq * (-768 + uSq * (320 - 175 * uSq)));
  356. double B = uSq / 1024 * (256 + uSq * (-128 + uSq * (74 - 47 * uSq)));
  357. double sigma = s / (b * A), sigmaP = 2 * Math.PI;
  358. double cos2SigmaM = 0, sinSigma = 0, deltaSigma = 0, cosSigma = 0;
  359. while (Math.abs(sigma - sigmaP) > 1e-12) {
  360. cos2SigmaM = Math.cos(2 * sigma1 + sigma);
  361. sinSigma = Math.sin(sigma);
  362. cosSigma = Math.cos(sigma);
  363. deltaSigma = B
  364. * sinSigma
  365. * (cos2SigmaM + B
  366. / 4
  367. * (cosSigma * (-1 + 2 * cos2SigmaM * cos2SigmaM) - B / 6 * cos2SigmaM
  368. * (-3 + 4 * sinSigma * sinSigma)
  369. * (-3 + 4 * cos2SigmaM * cos2SigmaM)));
  370. sigmaP = sigma;
  371. sigma = s / (b * A) + deltaSigma;
  372. }
  373. double tmp = sinU1 * sinSigma - cosU1 * cosSigma * cosAlpha1;
  374. double lat2 = Math.atan2(sinU1 * cosSigma + cosU1 * sinSigma * cosAlpha1, (1 - f)
  375. * Math.sqrt(sinAlpha * sinAlpha + tmp * tmp));
  376. double lambda = Math.atan2(sinSigma * sinAlpha1, cosU1 * cosSigma - sinU1 * sinSigma
  377. * cosAlpha1);
  378. double C = f / 16 * cosSqAlpha * (4 + f * (4 - 3 * cosSqAlpha));
  379. double L = lambda
  380. - (1 - C)
  381. * f
  382. * sinAlpha
  383. * (sigma + C * sinSigma
  384. * (cos2SigmaM + C * cosSigma * (-1 + 2 * cos2SigmaM * cos2SigmaM)));
  385. Location l = new Location(LocationManager.GPS_PROVIDER);
  386. l.setLatitude(Math.toDegrees(lat2));
  387. l.setLongitude(lon1 + Math.toDegrees(L));
  388. return l;
  389. }
  390. }