可以访问OpenStreetMap以获取地址的坐标
我正在尝试使用我在openstreetMap上找到的API检索给定地址的坐标,
API如下:
package com.sges.commons.utils.coordenada;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import org.json.simple.parser.JSONParser;
import com.sges.commons.generic.entities.GenConcelho;
public class OpenStreetMapUtils {
private static OpenStreetMapUtils instance = null;
private JSONParser jsonParser;
public OpenStreetMapUtils() {
jsonParser = new JSONParser();
}
public static OpenStreetMapUtils getInstance() {
if (instance == null) {
instance = new OpenStreetMapUtils();
}
return instance;
}
private static String getRequest(String url) throws Exception {
final URL obj = new URL(url);
final HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
int a = con.getResponseCode();
if (con.getResponseCode() != 200) {
return null;
}
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return response.toString();
}
public static Map<String, Double> getCoordinates(String address, String concelho) {
Map<String, Double> res;
StringBuffer query;
String join_morada_concelho = address + " " + concelho;
String[] split = join_morada_concelho.split(" ");
String queryResult = null;
query = new StringBuffer();
res = new HashMap<String, Double>();
query.append("http://nominatim.openstreetmap.org/search?q=");
if (split.length == 0) {
return null;
}
for (int i = 0; i < split.length; i++) {
query.append(split[i]);
if (i < (split.length - 1)) {
query.append("+");
}
}
query.append("&format=json&addressdetails=1");
try {
queryResult = getRequest(query.toString());
} catch (Exception e) {
}
if (queryResult == null) {
return null;
}
Object obj = JSONValue.parse(queryResult);
if (obj instanceof JSONArray) {
JSONArray array = (JSONArray) obj;
if (array.size() > 0) {
JSONObject jsonObject = (JSONObject) array.get(0);
String lon = (String) jsonObject.get("lon");
String lat = (String) jsonObject.get("lat");
res.put("lon", Double.parseDouble(lon));
res.put("lat", Double.parseDouble(lat));
}
}
return res;
}
}
问题是,当它到达GetRequest()方法时,它表明我没有响应代码200: 变量“ con”
是的,它会生成一个有效的URL,因为我将其粘贴到Chrome上,并且向我展示了我的地址坐标。 问题似乎是我的项目和OpenStreetMap之间的联系。
有什么想法吗?
I'm trying to retrieve coordinates for a given address using an API I found for OpenStreetMap
The API is as follows:
package com.sges.commons.utils.coordenada;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import org.json.simple.parser.JSONParser;
import com.sges.commons.generic.entities.GenConcelho;
public class OpenStreetMapUtils {
private static OpenStreetMapUtils instance = null;
private JSONParser jsonParser;
public OpenStreetMapUtils() {
jsonParser = new JSONParser();
}
public static OpenStreetMapUtils getInstance() {
if (instance == null) {
instance = new OpenStreetMapUtils();
}
return instance;
}
private static String getRequest(String url) throws Exception {
final URL obj = new URL(url);
final HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
int a = con.getResponseCode();
if (con.getResponseCode() != 200) {
return null;
}
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return response.toString();
}
public static Map<String, Double> getCoordinates(String address, String concelho) {
Map<String, Double> res;
StringBuffer query;
String join_morada_concelho = address + " " + concelho;
String[] split = join_morada_concelho.split(" ");
String queryResult = null;
query = new StringBuffer();
res = new HashMap<String, Double>();
query.append("http://nominatim.openstreetmap.org/search?q=");
if (split.length == 0) {
return null;
}
for (int i = 0; i < split.length; i++) {
query.append(split[i]);
if (i < (split.length - 1)) {
query.append("+");
}
}
query.append("&format=json&addressdetails=1");
try {
queryResult = getRequest(query.toString());
} catch (Exception e) {
}
if (queryResult == null) {
return null;
}
Object obj = JSONValue.parse(queryResult);
if (obj instanceof JSONArray) {
JSONArray array = (JSONArray) obj;
if (array.size() > 0) {
JSONObject jsonObject = (JSONObject) array.get(0);
String lon = (String) jsonObject.get("lon");
String lat = (String) jsonObject.get("lat");
res.put("lon", Double.parseDouble(lon));
res.put("lat", Double.parseDouble(lat));
}
}
return res;
}
}
The problem is that when it gets to the getRequest() method, it shows me that I don't have a response code 200:
variable "con"
And yes, it generates a valid URL because I pasted it on chrome and it showed me coordinates for my address.
The problem seems to be the connection between my project and OpenStreetMap.
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您必须做一些更好的错误处理。您会悄悄扔掉您回来的所有错误信息。
完全像这样挤压例外是一个好主意:
因此,将其更改为此:
然后您可以在
getRequest
方法中提供更多信息。您需要检查200个以外的响应代码。我认为,对于500个错误,您也可以从错误流中读取,尽管 [纠正此答案的早期版本] 也许不是严格必要的。希望有用的错误内容在主要响应流中,因此您需要类似的内容:
至少应该脱口而出系统。ERR
可能不是非常令人兴奋的错误信息。也许只是从OpenStreetMap的nominatim服务器回来的“ 403禁止”(由于违反),但请先设置它,以便您可以看到自己回来的内容。
You've got to do some better error handling. You're quietly throwing away all the error information that you get back.
It's rarely a good idea to squash exceptions entirely like this:
So change it to this:
And then you can throw an exception with more information in your
getRequest
method.You need to check for response codes other than 200. I think for 500 errors you also ideally read from errorStream, although [correcting earlier version of this answer] maybe it's not strictly necessary. Hopefully useful error content is in the main response stream so you need something like this:
That should at least blurt out something to System.err
It might not be very exciting error information. Maybe just a "403 forbidden" coming back from OpenStreetMap's nominatim server (due to violating the usage policy) but start by setting it up so you can see what you're getting back.
在您的情况下,您会收到
301
状态代码,因为您尝试使用nominatim
api的非安全版本。尝试将http
更改为https
,然后将获得结果。顺便说一句,如@harrywood所述,您应该适当地工作,而只是忽略了它们;而且您应该使用登录器为此。
In your case you receive
301
status code because you try to use non-secure version ofnominatim
API. Try to changehttp
tohttps
and you wil get a result.Btw as mentioned @HarryWood you should work with exceptions properly and just ignoring them; and you should use loggers for this.