我有一个java项目,我需要从地图中手动指定一个地方的纬度和经度。 我实际上是使用此代码来获取使用地址的经度和纬度:
public class LongLatService {
private static final String GEOCODE_REQUEST_URL = "http://maps.googleapis.com/maps/api/geocode/xml?sensor=false&";
private static HttpClient httpClient = new HttpClient(new MultiThreadedHttpConnectionManager());
public static void main(String[] args) throws Exception {
LongLatService tDirectionService = new LongLatService();
tDirectionService.getLongitudeLatitude("Rue Delangle, 58210 Varzy, France");
}
public void getLongitudeLatitude(String address) {
try {
StringBuilder urlBuilder = new StringBuilder(GEOCODE_REQUEST_URL);
if (StringUtils.isNotBlank(address)) {
urlBuilder.append("&address=").append(URLEncoder.encode(address, "UTF-8"));
}
final GetMethod getMethod = new GetMethod(urlBuilder.toString());
try {
httpClient.executeMethod(getMethod);
Reader reader = new InputStreamReader(getMethod.getResponseBodyAsStream(), getMethod.getResponseCharSet());
int data = reader.read();
char[] buffer = new char[1024];
Writer writer = new StringWriter();
while ((data = reader.read(buffer)) != -1) {
writer.write(buffer, 0, data);
}
String result = writer.toString();
System.out.println(result.toString());
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader("<"+writer.toString().trim()));
Document doc = db.parse(is);
String strLatitude = getXpathValue(doc, "//GeocodeResponse/result/geometry/location/lat/text()");
System.out.println("Latitude:" + strLatitude);
String strLongtitude = getXpathValue(doc,"//GeocodeResponse/result/geometry/location/lng/text()");
System.out.println("Longitude:" + strLongtitude);
} finally {
getMethod.releaseConnection();
}
} catch (Exception e) {
e.printStackTrace();
}
}
private String getXpathValue(Document doc, String strXpath) throws XPathExpressionException {
XPath xPath = XPathFactory.newInstance().newXPath();
XPathExpression expr = xPath.compile(strXpath);
String resultData = null;
Object result4 = expr.evaluate(doc, XPathConstants.NODESET);
NodeList nodes = (NodeList) result4;
for (int i = 0; i < nodes.getLength(); i++) {
resultData = nodes.item(i).getNodeValue();
}
return resultData;
}
}
但我希望从地图中获取经度和经度并在其他类中使用它们。
答案 0 :(得分:1)
我建议您使用Java Client for Google Maps Services来实现此目的。它是Google为全球Java开发人员开发的一个库,用于使用各种Google Map功能,如Geocoding,Direction API,Distance Matrix API等。在您的情况下,您可能正在使用Geocode API返回指定地址的LatLng 。您需要在项目中集成此库(可以与Maven和Gradle一起使用),然后只需几行代码即可获得通过Google地图传递的地址的纬度和经度。
以下是您需要为Geocode API使用的代码:
GeoApiContext context = new GeoApiContext().setApiKey("AIza...");
GeocodingResult[] results = GeocodingApi.geocode(context,
"1600 Amphitheatre Parkway Mountain View, CA 94043").await();
System.out.println(results[0].formattedAddress);
如果您不想使用此库并编写自己的代码,可以参考this project中的代码示例。
希望这有助于!!