2012-03-07 89 views
4

我無法從給定的郵政編碼中檢索經度和緯度值。我試圖通過一個Servlet來做到這一點,即將一個郵政編碼值傳遞給Servlet,然後Java代碼使用Google Geocode API檢索緯度和經度值,最好是以String形式。通過Java中的郵政編碼查找緯度和經度

我已經在網絡上漫遊了一個簡單的示例,但似乎有更多的JavaScript和PHP方法比Java更好。

難道有人可以粘貼一個簡單的樣本,如何以這種方式提取緯度/經度值?

在此先感謝!

-Rei

+1

你可以發佈你已經寫成了Servlet初始點? – radimpe 2012-03-07 10:52:15

+0

確保你也顯示地圖,否則你將違反Google的TOS。 – Matt 2012-03-08 00:44:25

回答

12

好長時間的答案。這是我用來成功詢問Google Geocode API的一些代碼。它要求GSON工作,但或者你也許可以手動解碼的答案,如果你不希望使用GSON:

import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStreamReader; 
import java.net.MalformedURLException; 
import java.net.URL; 
import java.net.URLEncoder; 

import org.slf4j.Logger; 

import com.google.gson.Gson; 
import com.google.gson.JsonIOException; 
import com.google.gson.JsonSyntaxException; 


public class GeoCoder { 
    private Gson gson = new Gson(); 

    private volatile long lastRequest = 0L; 

    public GeocodeResponse getLocation(String... addressElements) throws JsonSyntaxException, JsonIOException, MalformedURLException, 
      IOException { 
     StringBuilder sb = new StringBuilder(); 
     for (String string : addressElements) { 
      if (sb.length() > 0) { 
       sb.append('+'); 
      } 
      sb.append(URLEncoder.encode(string.replace(' ', '+'), "UTF-8")); 
     } 
     String url = "http://maps.googleapis.com/maps/api/geocode/json?sensor=false&address=" + sb.toString(); 
     // Google limits this web service to 2500/day and 10 requests/s 
     synchronized (this) { 
      try { 
       long elapsed = System.currentTimeMillis() - lastRequest; 
       if (elapsed < 100) { 
        try { 
         Thread.sleep(100 - elapsed); 
        } catch (InterruptedException e) { 
        } 
       } 
       return gson.fromJson(new BufferedReader(new InputStreamReader(new URL(url).openStream())), GeocodeResponse.class); 
      } finally { 
       lastRequest = System.currentTimeMillis(); 
      } 
     } 
    } 
} 

而其他類: GeocodeResponse:

import java.util.List; 

public class GeocodeResponse { 

    public enum Status { 
     OK, ZERO_RESULTS, OVER_QUERY_LIMIT, REQUEST_DENIED, INVALID_REQUEST; 
    } 

    public static class Result { 

     public static enum Type { 
      street_address, 
      route, 
      intersection, 
      political, 
      country, 
      administrative_area_level_1, 
      administrative_area_level_2, 
      administrative_area_level_3, 
      colloquial_area, 
      locality, 
      sublocality, 
      neighborhood, 
      premise, 
      subpremise, 
      postal_code, 
      natural_feature, 
      airport, 
      park, 
      point_of_interest, 
      post_box, 
      street_number, 
      floor, 
      room; 
     } 

     public static class AddressComponent { 

      private String long_name; 
      private String short_name; 
      private Type[] types; 

      public String getLong_name() { 
       return long_name; 
      } 

      public void setLong_name(String long_name) { 
       this.long_name = long_name; 
      } 

      public String getShort_name() { 
       return short_name; 
      } 

      public void setShort_name(String short_name) { 
       this.short_name = short_name; 
      } 

      public Type[] getTypes() { 
       return types; 
      } 

      public void setTypes(Type[] types) { 
       this.types = types; 
      } 
     } 

     private String formatted_address; 
     private List<AddressComponent> address_components; 
     private Geometry geometry; 
     private Type[] types; 

     public Type[] getTypes() { 
      return types; 
     } 

     public void setTypes(Type[] types) { 
      this.types = types; 
     } 

     public String getFormatted_address() { 
      return formatted_address; 
     } 

     public void setFormatted_address(String formatted_address) { 
      this.formatted_address = formatted_address; 
     } 

     public List<AddressComponent> getAddress_components() { 
      return address_components; 
     } 

     public void setAddress_components(List<AddressComponent> address_components) { 
      this.address_components = address_components; 
     } 

     public Geometry getGeometry() { 
      return geometry; 
     } 

     public void setGeometry(Geometry geometry) { 
      this.geometry = geometry; 
     } 

    } 

    public static class Geometry { 
     public static enum LocationType { 
      ROOFTOP, RANGE_INTERPOLATED, GEOMETRIC_CENTER, APPROXIMATE; 
     } 

     public static class ViewPort { 
      private Location northeast; 
      private Location southwest; 

      public Location getNortheast() { 
       return northeast; 
      } 

      public void setNortheast(Location northeast) { 
       this.northeast = northeast; 
      } 

      public Location getSouthwest() { 
       return southwest; 
      } 

      public void setSouthwest(Location southwest) { 
       this.southwest = southwest; 
      } 
     } 

     private Location location; 
     private LocationType location_type; 
     private ViewPort viewport; 

     public Location getLocation() { 
      return location; 
     } 

     public void setLocation(Location location) { 
      this.location = location; 
     } 

     public LocationType getLocation_type() { 
      return location_type; 
     } 

     public void setLocation_type(LocationType location_type) { 
      this.location_type = location_type; 
     } 

     public ViewPort getViewport() { 
      return viewport; 
     } 

     public void setViewport(ViewPort viewport) { 
      this.viewport = viewport; 
     } 

    } 

    private Status status; 
    private List<Result> results; 

    public Status getStatus() { 
     return status; 
    } 

    public void setStatus(Status status) { 
     this.status = status; 
    } 

    public List<Result> getResults() { 
     return results; 
    } 

    public void setResults(List<Result> results) { 
     this.results = results; 
    } 

} 

地點:

public class Location { 
    private double lat; 
    private double lng; 

    public Location() { 
    } 

    public Location(double lat, double lng) { 
     this.lat = lat; 
     this.lng = lng; 
    } 

    public double getLat() { 
     return lat; 
    } 

    public void setLat(double lat) { 
     this.lat = lat; 
    } 

    public double getLng() { 
     return lng; 
    } 

    public void setLng(double lng) { 
     this.lng = lng; 
    } 
} 
+0

您已經爲Gson示例投了票:-) – richj 2012-03-07 12:07:26

+0

謝謝! :)) – Wakka02 2012-03-08 04:36:37

+0

谷歌當前的地理編碼免費使用限制在此處列出[鏈接](https://developers.google.com/maps/documentation/geocoding/usage-limits) – NaanProphet 2017-12-30 14:18:09

5

這並不像Guillaume Polet的回答那樣優雅,但它不需要額外的庫。

有了說法:

"1600 Amphitheatre Parkway, Mountain View, CA" 

它打印出了答案:

Latitude: 37.42207610 
Longitude: -122.08451870 

下面是代碼:

import java.io.IOException; 
import java.io.InputStream; 
import java.net.URL; 


public class GoogleGeoCode 
{ 
    private static final String GEO_CODE_SERVER = "http://maps.googleapis.com/maps/api/geocode/json?"; 

    public static void main(String[] args) 
    { 
     String code = args[0]; 

     String response = getLocation(code); 

     String[] result = parseLocation(response); 

     System.out.println("Latitude: " + result[0]); 
     System.out.println("Longitude: " + result[1]); 
    } 

    private static String getLocation(String code) 
    { 
     String address = buildUrl(code); 

     String content = null; 

     try 
     { 
      URL url = new URL(address); 

      InputStream stream = url.openStream(); 

      try 
      { 
       int available = stream.available(); 

       byte[] bytes = new byte[available]; 

       stream.read(bytes); 

       content = new String(bytes); 
      } 
      finally 
      { 
       stream.close(); 
      } 

      return (String) content.toString(); 
     } 
     catch (IOException e) 
     { 
      throw new RuntimeException(e); 
     } 
    } 

    private static String buildUrl(String code) 
    { 
     StringBuilder builder = new StringBuilder(); 

     builder.append(GEO_CODE_SERVER); 

     builder.append("address="); 
     builder.append(code.replaceAll(" ", "+")); 
     builder.append("&sensor=false"); 

     return builder.toString(); 
    } 

    private static String[] parseLocation(String response) 
    { 
     // Look for location using brute force. 
     // There are much nicer ways to do this, e.g. with Google's JSON library: Gson 
     //  https://sites.google.com/site/gson/gson-user-guide 

     String[] lines = response.split("\n"); 

     String lat = null; 
     String lng = null; 

     for (int i = 0; i < lines.length; i++) 
     { 
      if ("\"location\" : {".equals(lines[i].trim())) 
      { 
       lat = getOrdinate(lines[i+1]); 
       lng = getOrdinate(lines[i+2]); 
       break; 
      } 
     } 

     return new String[] {lat, lng}; 
    } 

    private static String getOrdinate(String s) 
    { 
     String[] split = s.trim().split(" "); 

     if (split.length < 1) 
     { 
      return null; 
     } 

     String ord = split[split.length - 1]; 

     if (ord.endsWith(",")) 
     { 
      ord = ord.substring(0, ord.length() - 1); 
     } 

     // Check that the result is a valid double 
     Double.parseDouble(ord); 

     return ord; 
    } 
} 
+0

不過,感謝您花時間回答! :)) – Wakka02 2012-03-08 04:36:11

相關問題