地理编码器并不总是返回值

发布于 2024-10-02 17:44:33 字数 1201 浏览 0 评论 0原文

我能够成功获取纬度/经度并将其传递给地理编码器以获取地址。然而,我并不总是能得到地址。看来需要多尝试几次?我不知道为什么。

我现在有更好的方法来获取地址吗?

public List<Address> getAddresses(){
          Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
          List<Address> addresses = new ArrayList();
             try {
       addresses = geocoder.getFromLocation(latitude, longitude, 1);
      } catch (IOException e) {
       e.printStackTrace();
      }

      return addresses;
        }

我在这里调用这个方法:

LocationListener onLocationChange=new LocationListener() {
        public void onLocationChanged(Location loc) {
            //sets and displays the lat/long when a location is provided
            String latlong = "Lat: " + loc.getLatitude() + " Long: " + loc.getLongitude();   
            latitude = loc.getLatitude();
            longitude = loc.getLongitude();

            List<Address> addresses = getAddresses();

            if(addresses.size() > 0 && addresses != null)
             zipcode = addresses.get(0).getPostalCode();

            Toast.makeText(getApplicationContext(), zipcode,Toast.LENGTH_SHORT).show();
        }

I am able to successfully get lat/long and pass it to the geocoder to get an Address. However, I don't always get an address back. Seems like it takes a couple of attempts? I'm not sure why.

Is there a better way for me to obtain the address at this point?

public List<Address> getAddresses(){
          Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
          List<Address> addresses = new ArrayList();
             try {
       addresses = geocoder.getFromLocation(latitude, longitude, 1);
      } catch (IOException e) {
       e.printStackTrace();
      }

      return addresses;
        }

I am calling this method here:

LocationListener onLocationChange=new LocationListener() {
        public void onLocationChanged(Location loc) {
            //sets and displays the lat/long when a location is provided
            String latlong = "Lat: " + loc.getLatitude() + " Long: " + loc.getLongitude();   
            latitude = loc.getLatitude();
            longitude = loc.getLongitude();

            List<Address> addresses = getAddresses();

            if(addresses.size() > 0 && addresses != null)
             zipcode = addresses.get(0).getPostalCode();

            Toast.makeText(getApplicationContext(), zipcode,Toast.LENGTH_SHORT).show();
        }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

ぽ尐不点ル 2024-10-09 17:44:33

根据我的经验,谷歌地理编码器并不总是有效,我在地图上有几个固定点,当我点击叠加层时,它会弹出一个带有该纬度/经度地址的吐司,这些点不会改变,有时我点击同一个点 10 次,但我只得到其中 7 次的地址。

这很奇怪,但事实就是这样,我只是修改了我的应用程序来解决这个问题。

In my experience, Googles Geocoder doesn't always work, I have a couple of fixed points on the map, when I click on the overlay it pops a toast with the address for that lat/long, these points do not change, sometimes I click on a same point 10 times, but I only get an address 7 of them.

It's weird, but thats the way it is, I just modified my app to work around the problem.

旧竹 2024-10-09 17:44:33

上述方法以及互联网上的许多其他示例的问题在于,它们仅尝试使用 addresses.get(0).getPostalCode() 从第一个返回的提供程序检索数据。当您执行代码 List

时, addresses = getAddresses(),它检索提供者列表,每个提供者提供自己的数据。并非所有提供商都包含相同的数据。

我在接收邮政编码时遇到了同样的问题。在最初的测试中,我发现我正在接收来自 6 个提供商的数据。这 6 个提供商中只有 2 个返回了邮政编码。我尝试使用 address.get(0).getPostalCode() 访问的第一个提供商不是其中之一。更合适的方法是循环遍历所有返回的提供者,看看谁返回了我正在查找的数据。

像下面这样的东西应该有效。很有可能,其中一位提供商会返回邮政编码。可以对您需要由提供商返回的任何地理编码数据执行此操作。

List<Address> address = gc.getFromLocation(myLatitude, myLongitude, 10);

if (address.size() > 0) {
   strZipcode = address.get(0).getPostalCode();

   //if 1st provider does not have data, loop through other providers to find it.
   count = 0;
   while (strZipcode == null && count < address.size()) {
      strZipcode = address.get(count).getPostalCode();
      count++;
   }
}

The problem with the above approach, as well as many other examples around the internet, is that they only try to retrieve data from the first returned provider with addresses.get(0).getPostalCode(). When you execute the code List<Address> addresses = getAddresses(), it retrieves a list of providers, each supplying their own data. Not all providers will contain the same data.

I had the same issue with receiving the zip code. During my initial tests, I discovered I was receiving data from 6 providers. Only 2 of those 6 providers returned a zip code. The first provider I was trying to access with address.get(0).getPostalCode(), was not one of them. A more appropriate approach would be to loop through all the returned providers to see who returned the data I was looking for.

Something like the following should work. Odds are, one of the providers will return the zip code. This can be done for any of the Geocoding data that you need returned by the providers.

List<Address> address = gc.getFromLocation(myLatitude, myLongitude, 10);

if (address.size() > 0) {
   strZipcode = address.get(0).getPostalCode();

   //if 1st provider does not have data, loop through other providers to find it.
   count = 0;
   while (strZipcode == null && count < address.size()) {
      strZipcode = address.get(count).getPostalCode();
      count++;
   }
}
淡淡的优雅 2024-10-09 17:44:33

如果有人仍在寻找解决方案,这就是我所做的:
首先,我确保所有点都很好(会加载),但可能并不总是被地理编码捕获(获取数据是命中还是错过)
其次,我们强制代码做我们想要它做的事情,换句话说,如果我们知道它可以找到纬度和经度,那么就让它继续尝试,直到找到为止!这似乎也没有影响我的加载时间!所以这是代码:

do {
$geocode=file_get_contents('https://maps.google.com/maps/api/geocode/json?address='.$prepAddr.'&key='.$key.'sensor=false');

$output= json_decode($geocode);
$lat = $output->results[0]->geometry->location->lat;
$long = $output->results[0]->geometry->location->lng;
} while($lat == '' and $long == '');

这将继续循环,直到 lat 和 long 都不是空字符串!

快乐编码! :P

in case anyone is still looking for a fix, here is what i did:
first, i made sure that all the points were fine (would load) but may not always get grabbed by geocoding (getting the data is hit or miss)
second, we force the code to do what we want it to do, in other words, if we know it CAN find a lat and long, lets just make it keep trying until it does! this diddnt seem to effect my load time either! so here is the code:

do {
$geocode=file_get_contents('https://maps.google.com/maps/api/geocode/json?address='.$prepAddr.'&key='.$key.'sensor=false');

$output= json_decode($geocode);
$lat = $output->results[0]->geometry->location->lat;
$long = $output->results[0]->geometry->location->lng;
} while($lat == '' and $long == '');

this will continue to loop until both lat and long are not empty strings!

happy coding! :P

我不是你的备胎 2024-10-09 17:44:33

地理编码器在某些区域不起作用。您可以使用 Geocoding Api,而不是使用 Geocoder。请点击链接获取有关 api 的详细信息,

https://developers.google .com/s/results/?q=geocoding+api

Geocoder doesn't work in some area. Instead of using Geocoder, you can use Geocoding Api. Follow the link to get the details about the api,

https://developers.google.com/s/results/?q=geocoding+api

恬淡成诗 2024-10-09 17:44:33

如果您使用自动完成,您可以从 Place 对象获取地点位置:

private ResultCallback<PlaceBuffer> mUpdatePlaceDetailsCallback
        = new ResultCallback<PlaceBuffer>() {
    @Override
    public void onResult(PlaceBuffer places) {
        if (!places.getStatus().isSuccess()) {
            // Request did not complete successfully
            AALog.e("Geocoder Place query did not complete. Error: " + places.getStatus().toString());
            return;
        }
        // Get the Place object from the buffer.
        final Place place = places.get(0);
        //--------------here you can recover the place location---------------------
        ((DrawerActivity)getActivity()).lastPlace = place.getLatLng();
        //----------------------------------------------------------------------           
        places.release();
        getActivity().getFragmentManager().beginTransaction().remove(AutocompleteFragment.this).commit();
    }
};

此回调应在 AdapterView.OnItemClickListener 内注册如下:

        PendingResult<PlaceBuffer> placeResult = Places.GeoDataApi
                .getPlaceById(mGoogleApiClient, placeId);
        placeResult.setResultCallback(mUpdatePlaceDetailsCallback);

If you are using Autocomplete you can get place location from Place object:

private ResultCallback<PlaceBuffer> mUpdatePlaceDetailsCallback
        = new ResultCallback<PlaceBuffer>() {
    @Override
    public void onResult(PlaceBuffer places) {
        if (!places.getStatus().isSuccess()) {
            // Request did not complete successfully
            AALog.e("Geocoder Place query did not complete. Error: " + places.getStatus().toString());
            return;
        }
        // Get the Place object from the buffer.
        final Place place = places.get(0);
        //--------------here you can recover the place location---------------------
        ((DrawerActivity)getActivity()).lastPlace = place.getLatLng();
        //----------------------------------------------------------------------           
        places.release();
        getActivity().getFragmentManager().beginTransaction().remove(AutocompleteFragment.this).commit();
    }
};

This callback should be registered as follow inside AdapterView.OnItemClickListener:

        PendingResult<PlaceBuffer> placeResult = Places.GeoDataApi
                .getPlaceById(mGoogleApiClient, placeId);
        placeResult.setResultCallback(mUpdatePlaceDetailsCallback);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文