Geocoder getfromlocationname android studio

Android: обратное геокодирование-getFromLocation

Я пытаюсь получить адрес на основе long / lat. кажется, что-то вроде этого должно сработать?

проблема в том, что я продолжаю получать : метод Geocoder(Locale) не определен для типа savemaplocation

любая помощь была бы полезна. Спасибо.

спасибо, сначала я попробовал контекст, локаль один, и это не удалось, и я смотрел на некоторые другие конструкторы (я видел тот, который упомянул только локаль). Несмотря ни на что,

это не сработало, так как я все еще получаю : метод Geocoder(Context, Locale) не определен для типа savemaplocation

У меня есть: импорт android.местоположение.Геокодер;

8 ответов

следующий фрагмент кода делает это для меня (lat и lng являются двойниками, объявленными выше этого бита):

вот полный пример кода с использованием потока и обработчика для получения ответа геокодера без блокировки пользовательского интерфейса.

процедура вызова геокодера, может быть расположена в вспомогательном классе

вот вызов этой процедуры геокодера в вашей активности пользовательского интерфейса:

и обработчик, чтобы показать результаты в пользовательском интерфейсе:

Не забудьте поместить следующее разрешение в свой Manifest.xml

похоже, здесь происходит две вещи.

1) вы пропустили new ключевое слово перед вызовом конструктора.

2) параметр, который вы передаете конструктору геокодера, неверен. Вы проходите в Locale , где его ожидал Context .

есть два Geocoder конструкторы, оба из которых требуют Context , а также принимая Locale :

решение

измените код, чтобы передать его в допустимом контексте и включить new и вы должны быть хорошо идти.

Примечание

если у вас все еще есть проблемы, это может быть проблема с разрешением. Геокодирование неявно использует интернет для выполнения поиска, поэтому вашему приложению потребуется INTERNET тег uses-permission в манифесте.

добавить следующий узел uses-permission в manifest узел вашего манифеста.

причиной этого является несуществующая бэкэнд-служба:

класс геокодера требует бэкэнд-службы, которая не включена в основной Android framework. Методы запроса геокодера вернут пустой список, если в платформе нет серверной службы.

сначала получите широту и долготу, используя класс LocationManager и LocationManager. Теперь попробуйте код ниже для Get the city, address info

City info теперь находится в sb. Теперь преобразуйте sb в String (используя sb.toString ()).

Ну, я все еще в тупике. Итак, вот еще код.

прежде чем я оставлю свою карту, я звоню SaveLocation(myMapView,myMapController); это то, что заканчивается вызовом моей информации геокодирования.

но поскольку getFromLocation можете кинуть IOException , Я должен был сделать следующее, чтобы вызвать SaveLocation

тогда я должен изменить SaveLocation, сказав, что он бросает IOExceptions:

и он падает каждый раз.

Читайте также:  Прошивки для андроида wexler

Я слышал, что геокодер находится на стороне багги. Недавно я собрал пример приложения, которое использует службу геокодирования http Google для поиска местоположения из lat / long. Не стесняйтесь проверить это здесь

Источник

Geocoder. Get From Location Name Method

Definition

Some information relates to prerelease product that may be substantially modified before it’s released. Microsoft makes no warranties, express or implied, with respect to the information provided here.

Overloads

Returns an array of Addresses that attempt to describe the named location, which may be a place name such as «Dalvik, Iceland», an address such as «1600 Amphitheatre Parkway, Mountain View, CA», an airport code such as «SFO», and so forth.

Returns an array of Addresses that attempt to describe the named location, which may be a place name such as «Dalvik, Iceland», an address such as «1600 Amphitheatre Parkway, Mountain View, CA», an airport code such as «SFO», and so forth.

GetFromLocationName(String, Int32)

Returns an array of Addresses that attempt to describe the named location, which may be a place name such as «Dalvik, Iceland», an address such as «1600 Amphitheatre Parkway, Mountain View, CA», an airport code such as «SFO», and so forth.

Parameters

a user-supplied description of a location

max number of results to return. Smaller numbers (1 to 5) are recommended

Returns

a list of Address objects. Returns null or empty list if no matches were found or there is no backend service available.

Exceptions

if locationName is null

if the network is unavailable or any other I/O problem occurs

Remarks

Portions of this page are modifications based on work created and shared by the Android Open Source Project and used according to terms described in the Creative Commons 2.5 Attribution License.

Applies to

GetFromLocationName(String, Int32, Double, Double, Double, Double)

Returns an array of Addresses that attempt to describe the named location, which may be a place name such as «Dalvik, Iceland», an address such as «1600 Amphitheatre Parkway, Mountain View, CA», an airport code such as «SFO», and so forth.

Parameters

a user-supplied description of a location

max number of results to return. Smaller numbers (1 to 5) are recommended

the latitude of the lower left corner of the bounding box

the longitude of the lower left corner of the bounding box

the latitude of the upper right corner of the bounding box

the longitude of the upper right corner of the bounding box

Returns

a list of Address objects. Returns null or empty list if no matches were found or there is no backend service available.

Exceptions

if locationName is null

if any latitude is less than -90 or greater than 90

if any longitude is less than -180 or greater than 180

if the network is unavailable or any other I/O problem occurs

Читайте также:  Системный сервис для андроида

Remarks

Portions of this page are modifications based on work created and shared by the Android Open Source Project and used according to terms described in the Creative Commons 2.5 Attribution License.

Источник

Android: Reverse geocoding — getFromLocation

I am trying to get an address based on the long/lat. it appears that something like this should work?

The issue is that I keep getting : The method Geocoder(Locale) is undefined for the type savemaplocation

Any assistance would be helpful. Thank you.

Thanks, I tried the context, locale one first, and that failed and was looking at some of the other constructors (I had seen one that had mentioned just locale). Regardless,

It did not work, as I am still getting : The method Geocoder(Context, Locale) is undefined for the type savemaplocation

I do have : import android.location.Geocoder;

8 Answers 8

The following code snippet is doing it for me (lat and lng are doubles declared above this bit):

Here is a full example code using a Thread and a Handler to get the Geocoder answer without blocking the UI.

Geocoder call procedure, can be located in a Helper class

Here is the call to this Geocoder procedure in your UI Activity:

And the handler to show the results in your UI:

Don’t forget to put the following permission in your Manifest.xml

It looks like there’s two things happening here.

1) You’ve missed the new keyword from before calling the constructor.

2) The parameter you’re passing in to the Geocoder constructor is incorrect. You’re passing in a Locale where it’s expecting a Context .

There are two Geocoder constructors, both of which require a Context , and one also taking a Locale :

Solution

Modify your code to pass in a valid Context and include new and you should be good to go.

Note

If you’re still having problems it may be a permissioning issue. Geocoding implicitly uses the Internet to perform the lookups, so your application will require an INTERNET uses-permission tag in your manifest.

Add the following uses-permission node within the manifest node of your manifest.

Источник

Geocoder getFromLocationName is not finding address

Geocoder getFromLocationName is not returning anything if I’m searching for business places. Here are my finding so far:

  • grocery places, commercial buildings -> no result
  • schools -> finding results, but only returning Latitude and Longitude. I have to do reverse geocoding in order to get the address based on the coordinates, but the address wouldn’t be accurate.
  • complete address -> same as school, only returning Latitude and Longitude
  • hospital and pharmacy -> returning Latitude and Longitude

I’ve tested this on 1.6, 2.1 and 2.2 devices that has Google Maps.

I’m trying to find if there’s a limitation explained somewhere on the SDK, but there is none except:

The amount of detail in a reverse geocoded location description may vary, for example one might contain the full street address of the closest building, while another might contain only a city name and postal code. The Geocoder class requires a backend service that is not included in the core android framework. The Geocoder query methods will return an empty list if there no backend service in the platform (http://developer.android.com/reference/android/location/Geocoder.html)

[update] So after nights of research, I can’t seems to make it work — Google simply wont give me the result. Some discussion on android-developers points a fact that getFromBusinessName was omitted when Google Navigation came out. So I’m starting to assume that Google is pulling back some of their geocoding service.

Читайте также:  Смайл для андроид инстаграма

I can always create a webpage that use Google Geocoder API, but its limited to 2500 api call — and I dont think it will be legal (lol). So what are my alternatives here?

Источник

google maps API and geocoder.getFromLocationName

I want to search for GPS locations for with Google Maps. I have already registered with Google Maps API, and got the key. I can successfully pinpoint my current location on a map. The next part is to search for items around the current GPS location.

Approach 1: I tried using Android’s geocoder.getFromLocationName(«UPS»,5) but I am not getting anything.

Approach 2: hit Google https://maps.googleapis.cm/maps/apo/place/search but it needs a client id. To get a client id I have to create a premier account. Do I have to do all this?

Any suggestion how to use maps to search location for Android?

2 Answers 2

«GPS» is the place you’re looking up? Not a city or street name? I think that’s the problem here.

You will want to use a better «address» other than UPS to find locations using Geocoder. Do you realize how many UPS locations will be found. getFromLocationName() is best used with detailed location info and a locale directive so it limits its searching to the Locale you specify. Also, you will frequently get IOExceptions in the emulator. Lastly using SDK 2.3 and above will not work with Geocoder.

Try something like this:

Notice how the locale is set to US when I new up my Geocoder. Also notice the try catch around the call to geocoder. That will catch any IO Exceptions and allow you ot handle them as I did using a Toast message and some other flow control statements that are out of sight

Not the answer you’re looking for? Browse other questions tagged android google-maps or ask your own question.

Linked

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.12.3.40888

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

Оцените статью