简体   繁体   English

从给定的地址名称获取纬度和经度。不是地理编码器

[英]Get latitude & longitude from given address name. NOT Geocoder

I have an address name and I want to get an accurate latitude & longitude for it. 我有一个地址名称,我希望得到一个准确的纬度和经度。 I know we can get this using Geocoder's getFromLocationName(address,maxresult) . 我知道我们可以使用Geocoder的getFromLocationName(address,maxresult)来获取它。

The problem is, the result I get is always null - unlike the result that we get with https://maps.google.com/ . 问题是,我得到的结果总是为空 - 与我们通过https://maps.google.com/获得的结果不同。 This always allows me to get some results, unlike Geocoder. 与Geocoder不同,这总能让我得到一些结果。

I also tried another way: "http://maps.google.com/maps/api/geocode/json?address=" + address + "&sensor=false" (Here's a link !) It gives better results than geocoder, but often returns the error (java.net.SocketException: recvfrom failed: ECONNRESET (Connection reset by peer) . It's boring. 我还尝试了另一种方式: "http://maps.google.com/maps/api/geocode/json?address=" + address + "&sensor=false" (这是一个链接 !)它提供比地理编码器更好的结果,但经常返回错误(java.net.SocketException: recvfrom failed: ECONNRESET (Connection reset by peer) 。这很无聊。

My question is : How can we get the same latlong result we would get by searching on https://maps.google.com/ from within java code? 我的问题是 :如何通过在java代码中搜索https://maps.google.com/获得相同的latlong结果?

additional :where is the api document about using " http://maps.google.com/maps/api/geocode/json?address= " + address + "&sensor=false" 附加 :关于使用“ http://maps.google.com/maps/api/geocode/json?address=”+地址+“&sensor = false”的api文档在哪里

Albert, I think your concern is that you code is not working. 艾伯特,我认为你担心的是你的代码不起作用。 Here goes, the code below works for me really well. 在这里,下面的代码非常适合我。 I think you are missing URIUtil.encodeQuery to convert your string to a URI. 我认为你缺少URIUtil.encodeQuery来将你的字符串转换为URI。

I am using gson library, download it and add it to your path. 我正在使用gson库,下载并将其添加到您的路径中。

To get the class's for your gson parsing, you need to goto jsonschema2pojo . 要获得用于gson解析的类,您需要转到jsonschema2pojo Just fire http://maps.googleapis.com/maps/api/geocode/json?address=Sayaji+Hotel+Near+balewadi+stadium+pune&sensor=true on your browser, get the results and paste it on this site. 只需在浏览器上点击http://maps.googleapis.com/maps/api/geocode/json?address=Sayaji+Hotel+Near+balewadi+stadium+pune&sensor=true ,即可获得结果并将其粘贴到此网站上。 It will generate your pojo's for you. 它会为你生成你的pojo。 You may need to also add a annotation.jar. 您可能还需要添加annotation.jar。

Trust me, it is easy to get working. 相信我,很容易上班。 Don't get frustrated yet. 不要感到沮丧。

try {
        URL url = new URL(
                "http://maps.googleapis.com/maps/api/geocode/json?address="
                        + URIUtil.encodeQuery("Sayaji Hotel, Near balewadi stadium, pune") + "&sensor=true");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Accept", "application/json");

        if (conn.getResponseCode() != 200) {
            throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
        }
        BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));

        String output = "", full = "";
        while ((output = br.readLine()) != null) {
            System.out.println(output);
            full += output;
        }

        PincodeVerify gson = new Gson().fromJson(full, PincodeVerify.class); 
        response = new IsPincodeSupportedResponse(new PincodeVerifyConcrete(
                gson.getResults().get(0).getFormatted_address(), 
                gson.getResults().get(0).getGeometry().getLocation().getLat(),
                gson.getResults().get(0).getGeometry().getLocation().getLng())) ;
        try {
            String address = response.getAddress();
            Double latitude = response.getLatitude(), longitude = response.getLongitude();
            if (address == null || address.length() <= 0) {
                log.error("Address is null");
            }
        } catch (NullPointerException e) {
            log.error("Address, latitude on longitude is null");
        }
        conn.disconnect();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

The Geocode http works, I just fired it, results below Geocode http工作,我刚解雇它,结果如下

{
   "results" : [
      {
         "address_components" : [
            {
               "long_name" : "Pune",
               "short_name" : "Pune",
               "types" : [ "locality", "political" ]
            },
            {
               "long_name" : "Pune",
               "short_name" : "Pune",
               "types" : [ "administrative_area_level_2", "political" ]
            },
            {
               "long_name" : "Maharashtra",
               "short_name" : "MH",
               "types" : [ "administrative_area_level_1", "political" ]
            },
            {
               "long_name" : "India",
               "short_name" : "IN",
               "types" : [ "country", "political" ]
            }
         ],
         "formatted_address" : "Pune, Maharashtra, India",
         "geometry" : {
            "bounds" : {
               "northeast" : {
                  "lat" : 18.63469650,
                  "lng" : 73.98948670
               },
               "southwest" : {
                  "lat" : 18.41367390,
                  "lng" : 73.73989109999999
               }
            },
            "location" : {
               "lat" : 18.52043030,
               "lng" : 73.85674370
            },
            "location_type" : "APPROXIMATE",
            "viewport" : {
               "northeast" : {
                  "lat" : 18.63469650,
                  "lng" : 73.98948670
               },
               "southwest" : {
                  "lat" : 18.41367390,
                  "lng" : 73.73989109999999
               }
            }
         },
         "types" : [ "locality", "political" ]
      }
   ],
   "status" : "OK"
}

Edit 编辑

On 'answers do not contain enough detail` 在'答案不包含足够的细节'

From all the research you are expecting that google map have a reference to every combination of locality, area, city. 从所有的研究中,您期望谷歌地图可以参考当地,地区,城市的每个组合。 But the fact remains that google map contains geo and reverse-geo in its own context. 但事实仍然是谷歌地图在其自己的背景下包含地理和反向地理。 You cannot expect it to have a combination like Sayaji Hotel, Near balewadi stadium, pune . 你不能指望它有像Sayaji Hotel, Near balewadi stadium, pune这样的组合。 Web google maps will locate it for you since it uses a more extensive Search rich google backend. Web谷歌地图将为您找到它,因为它使用更广泛的Search丰富的谷歌后端。 The google api's only reverse geo address received from their own api's. 谷歌api唯一的反向地理地址是从他们自己的api收到的。 To me it seems like a reasonable way to work, considering how complex our Indian address system is, 2nd cross road can be miles away from 1st Cross road :) 对我而言,这似乎是一种合理的工作方式,考虑到我们的印度地址系统有多复杂,第二条十字路口距离第一条十字路口数英里:)

Here is a list of web services that provide this function. 以下是提供此功能的Web服务列表。

One of my Favorite is This 我最喜欢的是这个

Why dont you try hitting. 为什么不尝试击球。

http://api.geonames.org/findNearbyPlaceName?lat=18.975&lng=72.825833&username=demo http://api.geonames.org/findNearbyPlaceName?lat=18.975&lng=72.825833&username=demo

which returns following output.(Make sure you put your lat & lon in URL) 返回以下输出。(确保将lat&lon放在URL中)

在此输入图像描述

Hope this helps you: 希望这可以帮助你:

public static GeoPoint getGeoPointFromAddress(String locationAddress) {
        GeoPoint locationPoint = null;
        String locationAddres = locationAddress.replaceAll(" ", "%20");
        String str = "http://maps.googleapis.com/maps/api/geocode/json?address="
                + locationAddres + "&sensor=true";

        String ss = readWebService(str);
        JSONObject json;
        try {

            String lat, lon;
            json = new JSONObject(ss);
            JSONObject geoMetryObject = new JSONObject();
            JSONObject locations = new JSONObject();
            JSONArray jarr = json.getJSONArray("results");
            int i;
            for (i = 0; i < jarr.length(); i++) {
                json = jarr.getJSONObject(i);
                geoMetryObject = json.getJSONObject("geometry");
                locations = geoMetryObject.getJSONObject("location");
                lat = locations.getString("lat");
                lon = locations.getString("lng");

                locationPoint = Utils.getGeoPoint(Double.parseDouble(lat),
                        Double.parseDouble(lon));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return locationPoint;
    }

I use, in order: 我按顺序使用:
- Google Geocoding API v3 (in few cases there's a problem described here ) -谷歌地理编码API第3版(在少数情况下有描述的问题在这里
- Geocoder (in some cases there's a problem described here ). - Geocoder(在某些情况下, 这里描述一个问题)。

If I don't receive results from Google Geocoding API I use the Geocoder. 如果我没有收到Google Geocoding API的结果,我会使用Geocoder。

As far as I noticed Google Maps is using the Google Places API for auto complete and then gets the Details for the Location from which you can get the coordinates. 据我所知,谷歌地图使用Google Places API自动完成,然后获取位置的详细信息,您可以从中获取坐标。

https://developers.google.com/places/documentation/ https://developers.google.com/places/training/ https://developers.google.com/places/documentation/ https://developers.google.com/places/training/

This method should will give you the expected results. 这种方法应该会给你预期的结果。

String locationAddres = anyLocationSpec.replaceAll(" ", "%20");
URL url = new URL("https://maps.googleapis.com/maps/api/geocode/json?sensor=false&address="+locationAddres+"&language=en&key="YourKey");
try(InputStream is = url.openStream(); JsonReader rdr = Json.createReader(is)) {
    JsonObject obj = rdr.readObject();
    JsonArray results = obj.getJsonArray("results");
    JsonObject geoMetryObject, locations;

    for (JsonObject result : results.getValuesAs(JsonObject.class)) {
        geoMetryObject=result.getJsonObject("geometry");
        locations=geoMetryObject.getJsonObject("location");
        log.info("Using Gerocode call - lat : lng value for "+ anyLocationSpec +" is - "+locations.get("lat")+" : "+locations.get("lng"));
        latLng = locations.get("lat").toString() + "," +locations.get("lng").toString();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM