[英]Retrieve Coordinates from google maps api
我有一個地址列表,我現在想檢索它們的經度和緯度。 我想使用谷歌地圖 api 到 java。 我將如何 go 僅檢索一個地址的一組坐標。 (因為我可以輕松地實現多個)
您也可以像這樣使用 Google 地理編碼器 Java API GeoGoogle :
// Initialize a new GeoAddressStandardizer-class with your API-Key
GeoAddressStandardizer st = new GeoAddressStandardizer(apikey);
// Get a list of possible matching addresses
List<GeoAddress> addresses = st.standardizeToGeoAddresses(address);
// Get the first address (like you posted above)
GeoAddress address = addresses.get(0);
// Get the coordinates for the address
GeoCoordinate coords = address.getCoordinate();
// Longitude
double longitude = coords.getLongitude();
// Latitude
double latitude = coords.getLatitude();
這就是我最后的方式
public static String getCordinates(String address,String county) throws IOException, ParserConfigurationException, SAXException{
String thisLine;
address = address.replace(",", "+");
address = address.replace(" ", "+");
county = county.replace(" ", "");
String fullAddress = address+"+"+county;
System.out.println(fullAddress);
URL url = new URL("http://maps.google.com/maps/geo?q="+fullAddress+"&output=xml&key=ABQIAAAANGTAqDyDam_07aWkklK2NBSD41w" +
"X8VhCBpuiDVjGbFNuXE31lhQB8Gkwy-wmYbmaHIbJtfnlR9I_9A");
BufferedReader theHTML = new BufferedReader(new InputStreamReader(url.openStream()));
FileWriter fstream = new FileWriter("url.xml");
BufferedWriter out = new BufferedWriter(fstream);
while ((thisLine = theHTML.readLine()) != null)
out.write(thisLine);
out.close();
File file = new File("url.xml");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(file);
doc.getDocumentElement().normalize();
NodeList nl = doc.getElementsByTagName("code");
Element n = (Element)nl.item(0);
String st = n.getFirstChild().getNodeValue();
if (st.equals("200"))
{
NodeList n2 = doc.getElementsByTagName("coordinates");
Element nn = (Element)n2.item(0);
String st1 = nn.getFirstChild().getNodeValue();
return st1;
}
else
{
return null;
}
}
你可以用這個谷歌 API
將 API 與 restAssurd 一起使用是一種簡單的方法:
public static String[] getCoordinates(String address, String county) throws IOException, ParserConfigurationException, SAXException {
address = address.replace(",", "+");
address = address.replace(" ", "+");
county = county.replace(" ", "");
String fullAddress = address+"+"+county;
System.out.println(fullAddress);
URL url = new URL("http://maps.google.com/maps/api/geocode/json?address="+fullAddress+"&sensor=false");
Response res = given().
when().
get(url);
JsonPath jp = new JsonPath(res.asString());
String lat = jp.get("results.geometry.location.lat").toString();
String lng = jp.get("results.geometry.location.lng").toString();
String[] location = new String[2];
location[0] = lat;
location[1] = lng;
return location;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.