简体   繁体   中英

How would I store and display a location on Google Maps using the address entered by the user and not the lat or long?

我正在使用Android Studio制作用于分配任务的应用程序,如何在用户仅输入街道地址,城市,邮政编码/邮政编码后注销后将位置存储并显示在Google地图上并留在那里,国家/地区,而不是经纬度或长期坐标?

First you need to convert the address to a matching latitude longitude pair. So if I would enter Amsterdam , it would return the latitude and logitude of that city. This conversion is called geocoding. There's an Android tutorial for doing exactly this using the Geocoder class . If you want to just simple use the first value, here's an example with RxJava 2:

private Geocoder _geocoder;

public Observable<Location> convertAddressToLatLng(final String address) {
    if (_geocoder == null) {
        _geocoder = new Geocoder(_context);
    }
    return Observable.just(address)
            .map(new Func1<String, Location>() {
                @Override
                public Location call(String s) {
                    try {
                        List<Address> addressList = _geocoder.getFromLocationName(address, 1);
                        if (addressList != null && addressList.size() > 0) {
                            Address bestMatch = addressList.get(0);
                            Location result = new Location("");
                            result.setLatitude(bestMatch.getLatitude());
                            result.setLongitude(bestMatch.getLongitude());
                            return result;
                        } else {
                            return null;
                        }
                    } catch (IOException ex) {
                        Log.e(TAG, "Error while geocoding!", ex);
                        return null;
                    }
                 }
            })
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread());
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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