我使用谷歌地图 API 从谷歌地图 API 获取 GPS 坐标。我使用与我的老师代码几乎相似的代码,用于使用 api 中的 JSON。他使用来自 darksky 的 api,我使用来自谷歌地图的 API。
我的代码:
package com.company;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.nio.charset.Charset;
public class MyCoorGiver {
public final String API_URL = "https://maps.googleapis.com/maps/api/geocode/json?address=";
private String cityName;
private final String apiKey = "&key=";
private String fullUrl;
private String rawData;
JSONObject jsonObject;
private double lat;
private double lng;
public String getFullUrl() {
return fullUrl;
}
public MyCoorGiver(String cityName) {
this.cityName = cityName;
this.fullUrl = this.API_URL + cityName + this.apiKey;
}
private JSONObject readFromJsonUrl() throws IOException, JSONException {
InputStream is = new URL(this.fullUrl).openStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String jsonText = readAll(br);
jsonObject = new JSONObject(jsonText);
return jsonObject;
}
public String readAll(BufferedReader br) throws IOException {
StringBuilder sb = new StringBuilder();
int cp;
while((cp = br.read()) != -1){
sb.append(cp);
}
rawData = sb.toString();
return sb.toString();
}
public String getRaw(){
return rawData;
}
private double getLat() throws IOException, JSONException {
JSONObject myData = readFromJsonUrl();
JSONObject location = myData.getJSONObject("location");
double lat = location.getDouble("lat");
return lat;
}
private double getLng() throws IOException, JSONException {
JSONObject myData = readFromJsonUrl();
JSONObject location = myData.getJSONObject("location");
double lng = location.getDouble("lng");
return lng;
}
米脂
相关分类