我有一个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 –