Android地理编码功能不如iOS

时间:2015-08-11 14:41:46

标签: java android ios google-maps geocoding

所以我有一个将地址(String)转换成坐标的函数。

这就是iOS中的样子:

func setCoords(buildet: BuildingDetail) {

    let geoCoder = CLGeocoder()

    geoCoder.geocodeAddressString(buildet.address, completionHandler:
        {(placemarks: [AnyObject]!, error: NSError!) in

            if error != nil {
                println("Geocode failed with error: \(error.localizedDescription)")
            } else if placemarks.count > 0 {
                let placemark = placemarks[0] as! CLPlacemark
                let location = placemark.location
                buildet.lat = location.coordinate.latitude
                buildet.lon = location.coordinate.longitude
            }
            self.setupMarker(buildet)
    })
}

这就是Android中的样子:

public static double[] getLatLongPositions(String address) throws Exception
{
    int responseCode = 0;
    String api = "http://maps.googleapis.com/maps/api/geocode/xml?address=" + URLEncoder.encode(address, "UTF-8") + "&sensor=true";
    System.out.println("URL : "+api);
    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("/GeocodeResponse/status");
        String status = (String)expr.evaluate(document, XPathConstants.STRING);
        if(status.equals("OK"))
        {
            expr = xpath.compile("//geometry/location/lat");
            String latitude = (String)expr.evaluate(document, XPathConstants.STRING);
            expr = xpath.compile("//geometry/location/lng");
            String longitude = (String)expr.evaluate(document, XPathConstants.STRING);
            return new double[] {Double.parseDouble(latitude), Double.parseDouble(longitude)};
        }
    }
    return new double[]{0,0};
}

现在,上面的iOS函数只运行setupMarker函数,Android方法返回坐标,没什么大不了的!

我遇到的问题是,我正在为两个函数提供完全相同的地址参数。

iOS完美地返回所有坐标。

然而,Android只会正确地返回约30%。

是否有与上述iOS相同的Android功能,或只是可以正确地进行地理编码的功能。

正如您所见,Android在此处调用API:

http://maps.googleapis.com/maps/api/geocode/xml?address=

我测试了这个,它没有给出好的结果,至少不如iOS。

我该怎么办?

编辑 - 一些示例(所有适用于iOS)

  • EBS,2 Burlington Road,Dublin 2
  • AIB Bankcentre,Merrion Road,Ballsbridge,Dublin 4,Ireland
  • AIB,Unit 33,Sandyford Business Centre,Sandyford,Dublin 18

1 个答案:

答案 0 :(得分:1)

尝试使用以JSON格式返回数据的URL,然后您可以解析并获取纬度和经度。这是一个例子:

public static void getLatLongFromAddress(String youraddress) {
String uri = "http://maps.google.com/maps/api/geocode/json?address=" +
              youraddress + "&sensor=false";
HttpGet httpGet = new HttpGet(uri);
HttpClient client = new DefaultHttpClient();
HttpResponse response;
StringBuilder stringBuilder = new StringBuilder();

try {
    response = client.execute(httpGet);
    HttpEntity entity = response.getEntity();
    InputStream stream = entity.getContent();
    int b;
    while ((b = stream.read()) != -1) {
        stringBuilder.append((char) b);
    }
} catch (ClientProtocolException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

JSONObject jsonObject = new JSONObject();
try {
    jsonObject = new JSONObject(stringBuilder.toString());

    double lng = ((JSONArray)jsonObject.get("results")).getJSONObject(0)
        .getJSONObject("geometry").getJSONObject("location")
        .getDouble("lng");

    double lat = ((JSONArray)jsonObject.get("results")).getJSONObject(0)
        .getJSONObject("geometry").getJSONObject("location")
        .getDouble("lat");

    Log.d("latitude", "" + lat);
    Log.d("longitude", "" + lng);
} catch (JSONException e) {
    e.printStackTrace();
}

} 

希望这会有所帮助。