PageRenderTime 40ms CodeModel.GetById 13ms app.highlight 23ms RepoModel.GetById 1ms app.codeStats 0ms

/there/src/com/google/marvin/there/StreetLocator.java

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