我有一個JAVA程序從URL中提取數據。Java獲取谷歌地圖信息
Extract.java
public class Uni_Extract {
protected static String lat;
protected static String lng;
public static void main(String[] args) throws Exception {
System.out.println("Started");
String csvFile = "C://Users/Kennedy/Desktop/university.csv";
FileWriter writer = new FileWriter(csvFile);
for (int i=2; i<=2; i++){
String url = "http://www.4icu.org/reviews/index"+i+".htm";
Document doc = Jsoup.connect(url).userAgent("Mozilla").get();
Elements cells = doc.select("td.i");
Iterator<Element> iterator = cells.iterator();
while (iterator.hasNext()) {
Element cell = iterator.next();
String university = Jsoup.parse((cell.select("a").text())).text();
String country = cell.nextElementSibling().select("img").attr("alt");
LatLngBackup LatLngBackup = new LatLngBackup();
LatLngBackup.getLatLongPositions(university);
System.out.print(university);
System.out.printf(", lat : %s, lng : %s %n", lat, lng);
CSVUtils.writeLine(writer,Arrays.asList(country,university,lat,lng),',','"');
}
}
writer.flush();
writer.close();
}
}
然後我還呼籲Java類經緯度呼籲從谷歌地圖API的經度和緯度。
public class LatLngBackup extends Uni_Extract
{
public String[] getLatLongPositions(String address) throws Exception
{
int responseCode = 0;
String api = "https://maps.googleapis.com/maps/api/place/textsearch/xml?query=" + URLEncoder.encode(address, "UTF-8") +
"&key=AIzaSyCTBvomwAMvq0pSxgN0y2I_wALFJ8cx57Y";
URL url = new URL(api);
HttpURLConnection httpConnection = (HttpURLConnection)url.openConnection();
httpConnection.connect();
responseCode = httpConnection.getResponseCode();
if(responseCode == 200)
{
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();;
Document document = builder.parse(httpConnection.getInputStream());
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
XPathExpression expr = xpath.compile("/PlaceSearchResponse/status");
String status = (String)expr.evaluate(document, XPathConstants.STRING);
if(status.equals("OK"))
{
expr = xpath.compile("//geometry/location/lat");
super.lat = (String)expr.evaluate(document, XPathConstants.STRING);
expr = xpath.compile("//geometry/location/lng");
super.lng = (String)expr.evaluate(document, XPathConstants.STRING);
return new String[] {lat, lng};
}
else
{
super.lat="";
super.lng="";
}
}
return null;
}
}
但是,它給了我一個達到API密鑰請求限制的消息。有沒有其他的方法可以做到這一點?
也許你應該使用例如sigleton來防止每次調用這個函數時進行連接。當然你應該閱讀一些關於OOP的內容。 –
支付訂閱谷歌服務,所以你可以要求所有你需要的數據。免費的API密鑰用於開發目的,並有一個請求限制。 –
@ shutdown-hnow可否請您解釋一下。我不是那種使用Google Map API和JAVA的expoertise –