Android studio osm карты

«Hello osmdroid World»

osmdroid’s MapView is basically a replacement for Google’s MapView class. First of all, create your Android project, and follow HowToMaven if you’re using Maven, or follow HowToGradle if you’re using Gradle/Android Studio. This will help you get the binaries for osmdroid included in your project.

Manifest

In most cases, you will have to set the following authorizations in your AndroidManifest.xml:

If you are only using parts of the library, you can adjust the permissions accordingly.

Online tile provider

Offline tile provider and storing tiles

Location provider

Android 6.0+ devices require you have to check for «dangerous» permissions at runtime.
osmdroid requires the following dangerous permissions:
WRITE_EXTERNAL_STORAGE and ACCESS_COARSE_LOCATION/ACCESS_FINE_LOCATION.
See OpenStreetMapViewer’s implementation or Google Documentation on Permissions

Layout

Create a «src/main/res/layouts/main.xml» layout like this one. With Android Studio, it probably created one already. The default is called «src/main/res/layouts/activity_main.xml»:

Main Activity

We now create the main activity (MainActivity.java):

And that’s enough to give it a try, and see the world map.

Then we add default zoom buttons, and ability to zoom with 2 fingers (multi-touch)

We can move the map on a default view point. For this, we need access to the map controller:

Advanced tutorial

The best example of how to use the osmdroid library is our OpenStreetMapViewer sample project. It contains a basic osmdroid application plus a few special-use examples. It is recommended you use this project as an example for building your application.

Adding a MapView

You can add a MapView to your xml layout using:

This will allow you to configure the tile source imagery for your MapView but not much else.

However, for more control over your MapView , you will want to create a MapView programmatically.

Images for Buttons and whatnot

For osmdroid 4.3 and older, there’s a number of resources that the map uses for various user interface helpers, such as zoom in/out buttons, the device’s current location when GPS is available and more. These resources are loaded via the «ResourceProxy». The idea is that you can either bring your own images or borrow the ones from osmdroid. If you’re borrowing, then you’ll want to grab the files located here and add them to your project «src/main/res/drawable».

For osmdroid 5.0 and 5.1, the drawables are included with the AAR package. The resource proxy is still present and used so you can override values and images as needed.

For osmdroid 5.2 and up, the resource proxy is removed from the API set and replaced with Android context.

Create a custom Resource Proxy

Applies only to versions prior to 5.2

As mentioned above, the Resource Proxy is a bit of a strange animal that osmdroid uses to load some images for user interface controls. If you’re using any of the built-in controls that need images (zoom in/out, person icon, etc) you’ll either need to provide your own images, borrow the images from osmdroid’s example app, or provide your own implementation of Resource Proxy.

Читайте также:  Ошибка при установке обновления android

The example osmdroid app includes an example of this called CustomResourceProxy (included with > 4.3 osmdroid). All it does is change the my location drawable (person) to an alternate image. The example is below.

Then you can use your instance using the following snippet.

In order to see any difference with our example (changes the person icon), we’ll need to get a location fix and add it to the map layers.

Map Overlays

How to add the My Location overlay

Note: you need manifest Fine Location permissions and if you are targeting API23+ APIs, you have to ask the user to explicitly grant location runtime permissions.

Notice: this is a very simple example that does not handle android lifecycle correctly. Versions 5.6.5 and older, you’ll need to handle automatically disabling/enabling the location provider with android life cycle events. Version 6.0.0, this is handled so long as you call map view onPause and onResume appropriately.

How to add a compass overlay

Notice: this is a very simple example that does not handle android lifecycle correctly. Versions 5.6.5 and older, you’ll need to handle automatically disabling/enabling the compass/orientation provider with android life cycle events. Version 6.0.0, this is handled so long as you call map view onPause and onResume appropriately.

How to enable the Grid line Overlay

Useful for displaying latitude/longitude grid lines.

v5.2 up to v5.6.5, see the sample app’s source code from those tagged versions.

How to enable rotation gestures

How to add Map Scale bar overlay

How to add the built-in Minimap

Note: do not use when rotation is enabled! (Keep reading for a work around)

Versions 5.6.5 and older: If you want the minimap to stay put when rotation is enabled, create a second map view in your layout file, then wire up a change listener on the main map and use that to set the location on the minimap. For the reverse, you need to do the same process, however, you have to filter map motion events to prevent infinite looping. There’s an example on how to sync the views within the example application.

Version 6.0.0: the above tip is no longer necessary.

How do I place icons on the map with a click listener?

How many icons can I put on the map?

The answer is greatly dependent on what hardware the osmdroid based app is running on. A Samsung S5 (no endorsement intended) ran just fine at 3k icons and was noticeably choppy at 6k icons. Your mileage may vary. X86 Android running on modern hardware will perform great at even higher numbers. However, it’s recommended to limit the amount of stuff you’re rendering, if at all possible.

If you’re also drawing paths, lines, polygons, etc, then this also changes the equation. Drawing multipoint graphics is computationally more expensive and thus negatively affects performance under higher loads. To mitigate performance issues with multipoint graphics, one strategy would be to reduce the number of points handed off to the map engine when at a higher zoom level (numerically lower), then increase the fidelity as the user zoom’s in. In effect, you would be clipping the visible data at the map view bounds so that the map view only «knows» about what’s on screen and doesn’t have to loop through all 10k icons that you want on the map. Although you can give the map view all 10k objects, but every time the map moves or zooms, it will iterate over all 10k items to calculate where to draw them (if at all). Using this mechanism paired with map motion listeners and a database query that supports geographic bounds, you can support a rich experience for users with lots of data and still have reasonable performance.

Читайте также:  Android auto версия андроида

Reusing drawables for icons will help with memory usage too.

Map Sources, Imagery and Tile sets.

Using osmdroid in a recycler view

Applies to: v5.6.5 and older. (v6.0.0 has this fix applied already)

It has been brought up a view times that osmdroid’s MapView does not play nicely in a RecyclerView . The MapView is a custom android ViewGroup that implements the necessary API calls that ViewGroup requires, namely onDetachedFromWindow. In this function call, osmdroid basically calls destructors on all associated overlays, threading, tile loading, etc. This is destructive and cannot be reinitialized. This was done primarily to prevent memory leaks. Since ViewGroup does not have a destroy method or anything else that happens during garbage collection, this is really the only place we can put clean up code. As such, using the map in a recycler view won’t work without this simple one liner.

Now naturally, this will only function on devices at API16 (Jelly Bean) and newer so the recommendation is to simply not use osmdroid in a recycler view for older APIs. The alternative approach is for you to extend the MapView and override the method for public void onDetach() and simply provide an empty body. This will create memory leaks though so use with caution.

Источник

Как использовать карту OSM в приложении для android.? Есть ли учебник, чтобы узнать об использовании OSM в android.?

Привет, ребята из прошлой недели я ищу учебник / руководство или шаги, чтобы включить открытую карту улиц в мое приложение для android. Все, что я нашел, — это либо большой проект с гораздо большей функциональностью, либо так много вопросов закончилось без надлежащего вывода о «как».

есть ли какой-либо правильный блог/сайт или документ, на который может ссылаться более свежий.?

4 ответов

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

обратите внимание, что теперь вы должны использовать последнюю версию (4.1), чтобы избежать блокировки загрузки плиток из OSM.

также обратите внимание, что они перемещают свои репозитории в Github, и процесс еще не завершен. Эта страница скачать держит ссылки для банок

этот образец проекта OSMdroid это, безусловно, самый простой,что я столкнулся. Не более 5 минут, чтобы быть запущен и работает. Обратите внимание на файл манифеста.

для немного большей сложности,в этом уроке выводит карту с текущей геопоинт.

вот некоторые фрагменты из различных проектов. Но не все из них проверил.

вы должны скачать OSMdroid и SLF4J, в , Add as Library osmdroid, исправить AndroidManifest.xml с соответствующими разрешениями (см. первый учебник). Если вы это сделаете, нет необходимости изменять gradle.build файл, как рекомендовано в первом уроке.

Я рекомендую вам использовать для начала более старые версии osmdroid (3.х) при использовании этих. Как только вам будет удобно, перейдите на более новую версию osmdroid (4.x или 5.икс.)

классы GeoPoint и MapController меняют имена в более новых версии, так что следите за НЕСОВМЕСТИМЫЕ ТИПЫ ОШИБКА

IGeoPoint не может быть преобразован в GeoPoint

IMapController не может быть преобразован в MapController

Читайте также:  Как включить режим отладки usb android через компьютер

Я объяснил шаги здесь. Я также рекомендую вам взглянуть на их Пример Проекта что очень полезно. И их документация о как 😉

и Автономного Использования

1 — Вы должны скачать карту, используя MOBAC.

2-Поместите его в /mnt/sdcard/osmdroid/

после этих шагов все то же самое, что объяснил @Nick.

одна ошибка, которую делают люди, использующие Google Maps, как сервис, заключается в том, что они рассматривают OpenStreetMap как просто поставщика плитки карты. Вы должны знать, что OpenStreetMap на самом деле является большой бесплатной редактируемой базой геоданных wiki, и есть три разных способа использования этой базы данных.

Источник

Android studio osm карты

osmdroid

osmdroid is a (almost) full/free replacement for Android’s MapView (v1 API) class. It also includes a modular tile provider system with support for numerous online and offline tile sources and overlay support with built-in overlays for plotting icons, tracking location, and drawing shapes.

Current Release: 6.1.10 Jan 30, 2021

Current Development version: 6.1.11-SNAPSHOT

Next Release Version (planned): 6.1.11

Note: check your calendar, it may take up to a few days for all global mirrors to update.

Please read the osmdroid wiki for tutorials on integration.

Gradle dependency

Be sure to replace with the last release version above.

Maven dependency

Platform or API Level (API level 8 = Platform 2.2)

Want the latest and greatest?

We periodically publish snapshots to maven central. If you’re interesting in trying it out, using the following:

Use at your own risk though, it may not be stable or may have bugs or performance issues. If you run across any, please report them.

Side note: gradle’s cached dependencies and doesn’t really handle snapshot very well. To force gradle to update snapshots on every build, try adding this to your root build.gradle file.

You can also build your project using the gradle option —refreshDependencies

Related and important wiki articles

I have a question or want to report a bug

If you have a question, please view the osmdroid FAQ.
You can also view the Stack Overflow osmdroid tag and osmdroid Google Group where you can get feedback from a large pool of osmdroid users.

If you still have an issue, please check the Changelog page to see if this issue is fixed in a newer or upcoming version of osmdroid.

If think you have a legitimate bug to report then go to the Issues page to see if your issue has been reported. If your issue already exists then please contribute information that will help us track down the source of the issue. If your issue does not exist then create a new issue report. When creating an issue, please include the version of osmdroid, the Android platform target and test device you are using, and a detailed description of the problem with relevant code. It is particularly helpful if you can reproduce the problem using our OpenStreetMapViewer sample project as your starting point.

I want to contribute

For your reference, the dashboard provides a high level overview of the repository including structure of UI classes, module dependencies, external libraries, and other components of the system.

The OSMBonusPack project adds additional functionality for use with osmdroid projects.

Building from source and using the aar in your app

Thanks to Gradle Fury, this publishes the artifacts to mavenLocal.

In your root build.gradle file, add mavenLocal() if not present.

Then in your APK or AAR project that needs osmdroid.

Источник

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