- Google MAPs API в android или как работать с картами быстрее
- Принцип работы Google MAPs API
- А как вообще работать с этой страшной штукой?
- Подключение библиотеки
- Встраиваем карту в приложение
- Пишем всякие интересности
- 10 Free Offline GPS Maps For Android And iOS – No Internet Data Connections
- ↓ 01 – Organic Maps | Open Source | Android | iOS
- ↓ 02 – Google Maps | Free [ With Ads ] | Android | iOS
- ↓ 03 – OsmAnd | In-App Purchase | Android | iOS
- ↓ 04 – HERE WeGo | Free [ with Ads ] | Android | iOS
- ↓ 05 – MAPS.ME | In-App Purchase | Android | iOS
- ↓ 06 – Navmii GPS World | In-App Purchase | Android | iOS
- ↓ 07 – Yandex.Maps | Free [ With Ads ] | Android | iOS
- ↓ 08 – Karta GPS | In-App Purchase | Android | iOS
- ↓ 09 – Magic Earth | 100% Free | Android | iOS
- ↓ 10 – 2GIS | Free [ With Ads ] | Android | iOS
- ↓ 11 – TomTom GO Mobile | Paid | Android | iOS
- ↓ 12 – Garmin StreetPilot Onboard [ Discontinued ] | USD60 | iOS
- How GPS Works?
Google MAPs API в android или как работать с картами быстрее
Принцип работы Google MAPs API
Вся документация для работы с картами приведена на (логично) официальном сайте google maps api. Сегодня я рассматриваю только Directions API (документация). Для того что бы получить какую-либо информацию от большого числа, вам необходимо сделать запрос. Ответ прийдет в формате JSON.
Общий вид запроса:
Пример: https://maps.googleapis.com/maps/api/directions/json?origin=55.754724,%2037.621380&destination=55.728466,%2037.604155&key=»Your MAPs API key»
В качестве ответа нам (ожидаемо) пришел JSON с большим набором разных точек с координатами и названиями этих мест.
А как вообще работать с этой страшной штукой?
Если вы только начинаете работать с Android, то советую вам почитать про такую замечательную библиотеку Retrofit, которая превращает работу с запросами в код из 2 строк. Рассматривать сейчас я её не буду.
Но я сегодня хочу рассмотреть пример использования библиотеки Java Client for Google Maps Services. Библиотека как по мне замечательная, освобождает от необходимости писать (пусть даже очень короткие) запросы вручную и отлично подходит в случаях когда нужно писать очень быстро, как например на хакатоне. Я хочу показать живой пример использования данной библиотеки на примере работы с Directions API.
Подключение библиотеки
Для начала нам потребуется получить ключ для нашего приложения. Топаем на оф. сайт, находим сверху кнопку «получить ключ», создаем новый проект, нажимаем далее и готово!
UPD: теперь бесплатно получить нельзя. С лета 2018 года Google обновили план и необходимо ввести данные своей карты для получения 200$ для запросов каждый месяц бесплатно. Этого должно хватать, но конечно тенденция не радует.
Firebase
Для правильной работы приложения нам необходимо получить файл google-service.json. Идем на firebase выбираем наш проект и добавляем его. Далее нам нужно выбрать Android проект, ввести название пакета, регистрируем приложение. Скачиваем файл и перетаскиваем в папку app. К слову её не будет видно в дереве проекта, для этого надо в Android Studio поменять отображение с Android на Project или залезть в наш проект через файловый менеджер. Далее следуем инструкциям где какой код писать.
Включаем в консоли
Так же нам необходимо включить Directions API (или любую другую необходимую вам API) в консоли, для этого идем сюда, выбираем наше приложение и включаем Directions API.
Gradle
В Gradle файлы так же необходимо добавить еще пару строк. В итоге новые строки выглядят вот так:
Обязательно проверяйте, актуальная ли это сейчас версия!
Встраиваем карту в приложение
Google map в андроид реализовывается как фрагмент (или как MapView, но об этом в другой раз, нам сейчас особой разницы нет). Просто встраиваем его в наш layout. В нашем классе, который работает с картой, необходимо найти эту карту и заимплементить интерфейс.
Код для фрагмента выглядит вот так. Я буду работать с MainActivity, соответственно если вы используете другой класс вам необходимо поменять контекст.
Отлично, фрагмент встроили, Android Studio на нас не ругается, едем дальше. Переходим в MainActivity.class и имплементим интерфейс OnMapReadyCallback.
В onCreate пишем
Так же идем в Manifests и прописываем вот такие штуки внутри тэга application
Где вместо @string/google_maps_key должен подставиться ваш ключ для карт, который мы получили ранее. Соответственно вам нужно создать нужный ресурс в файле string.
Пишем всякие интересности
Отлично, карта у нас есть, давайте наконец напишем хоть что-нибудь интересное. Пусть нашей целью будет нарисовать маршрут по Москве через несколько точек:
- Гум (55.754724, 37.621380)
- Большой театр (55.760133, 37.618697)
- Патриаршие пруды (55.764753, 37.591313)
- Парк культуры (55.728466, 37.604155)
Кладу все наши места в List и делаю это как глобальную переменную.
Для начала создадим по маркеру на каждое место. Маркер это просто объект, которому передаются координаты, а затем они накладываются на карту. Код:
Далее мы пишем вот такой код все в том же методе onMapReady
При запуске приложения мы получили вот такую картину:
Хм, Москва, конечно, весьма запутанная, но не настолько же. Почему же такой странный маршрут нам вернул Google? Потому что он построил маршрут для автомобилей, который идет по умолчанию, но мы можем это изменить. Чтобы построить маршрут для пешеходов, меняем код на:
Теперь наш маршрут выглядит вот так
Существует еще множество настроек, о всех них можно прочитать в документации. Просто мы все параметры будем добавлять не в сырой запрос, а в код, поскольку методы библиотеки имеют те же названия что и просто в запросах.
Источник
10 Free Offline GPS Maps For Android And iOS – No Internet Data Connections
Casual drivers don’t use a dedicated Garmin or TomTom GPS Navigator anymore, with the birth of better smartphones, it doesn’t make any sense to buy a device with 1 function when an Android smartphone or iPhone can perform the same task for free. Google Maps is the most informative map app, and Waze is possibly the best when it comes to driving. Unfortunately, Waze doesn’t offer an offline feature because it defeats the purpose of the app – avoiding traffic by finding the least congested route.
For those without a mobile internet connection, why waste precious money prepaid for mobile data when there are so many offline turn by turn navigation apps? There are many good Apple Maps and Waze alternatives. Here are some of the best GPS offline navigation apps without internet connection for Google Android Smartphone and Apple iOS iPhone.
↓ 01 – Organic Maps | Open Source | Android | iOS
Organic Maps is an Android & iOS offline maps app for travelers, tourists, hikers, and cyclists based on top of crowd-sourced OpenStreetMap data and curated with love by MapsWithMe founders. Organic Maps is an indie community-driven open-source project.
- Detailed offline maps with places that don’t exist on other maps
- Cycling routes, hiking trails and walking paths
- Contour lines, elevation profiles, peaks and slopes
- Turn-by-turn walking, cycling and car navigation with voice guidance
- Fast offline search on the map and bookmarks
- Dark mode to protect your eyes
↓ 02 – Google Maps | Free [ With Ads ] | Android | iOS
Google Maps requires no introduction. Offline Maps is now available for Google Maps and requires no internet or data connection, simply select the area and download it. The maps will expire after 30 days, all you have to do is re-download it.
If you’re going where the Internet is slow, mobile data is expensive, or you can’t get online, you can save an area from Google Maps to your phone or tablet and use it when you’re offline. Note: Downloading offline maps isn’t available in some regions because of contractual limitations, language support, address formats, or other reasons.
↓ 03 – OsmAnd | In-App Purchase | Android | iOS
OsmAnd Maps is a map application with access to the free, worldwide, and high-quality OpenStreetMap (OSM) data. All map data can be stored on your device’s memory card for offline use. All the main functionalities work both online and offline (no internet needed). Enjoy voice and optical navigator, viewing POIs (points of interest), creating and managing GPX tracks, using contour lines visualization and altitude info (through plugin), a choice between driving, cycling, pedestrian modes, OSM editing and much more.
- Works totally offline (no roaming charges when you are abroad) but also has a (fast) online option
- Turn-by-turn voice guidance (recorded and synthesized voices)
- Carry highly detailed, fully offline maps of any region world wide on your device!
- Unlimited free map downloads, directly from the app (download limit 7 map files in the free version)
- Always up-to-date maps (updated at least once a month)
↓ 04 – HERE WeGo | Free [ with Ads ] | Android | iOS
HERE WeGo is a free app that makes city navigation effortless. With detailed routes, turn-by-turn guidance and information about every way of getting around, it’s the only app you need to get through the city. HERE WeGo offers transport information in 1300 cities around the world including: New York City / NYC, San Francisco / SF, London, Berlin, Munich, Paris, Barcelona, Madrid, Rome, Milan, Vancouver, Toronto, Sydney, Melbourne and many more.
Get to where you need to go via subway / metro / underground, bus, bike, train, tram, or ferry. HERE WeGo has offline maps of the United States, the United Kingdom, Germany, France, Spain, Italy, Canada, Australia and more than 100 other countries around the world. Download the map you want and you’re set!
↓ 05 – MAPS.ME | In-App Purchase | Android | iOS
Free, fast, detailed and entirely offline maps with turn-by-turn navigation – trusted by over 50 million travelers worldwide. MAPS.ME offers the quickest offline maps of all the countries of the world. Travel with full confidence: wherever you are, MAPS.ME addresses all your offline mapping needs. Need a map of London or a map of New York? A map of Paris or Rome? Any country, any place, from the largest cities to small villages, in MAPS.ME!
- Offline Maps – Save mobile data; no internet is required.
- Free Forever – All maps inside and all features are free. Always were and will always be.
- Navigation – Use driving, walking and cycle navigation anywhere in the world.
- Incredible Detailed – Directions to points of interest (POIs), hiking trails and places missing from other maps.
- Up-To-Date – Maps are updated by millions of OpenStreetMap contributors daily. OSM is an open-source alternative to Google Maps and Apple Maps.
- Fast And Reliable – Offline search, GPS navigation along with optimized maps to effectively save memory space.
↓ 06 – Navmii GPS World | In-App Purchase | Android | iOS
Navmii World is the world’s leading navigation app for drivers, giving you free access to maps and navigation for every country, now in a single app. All maps, map updates and features are completely free. Offline maps for reliable navigation at home or abroad without an internet connection. Trusted by over 24 million drivers worldwide.
- Turn-by-turn voice-guided navigation
- 197 countries available (download one, multiple or all)
- GPS navigation
- Offline maps
↓ 07 – Yandex.Maps | Free [ With Ads ] | Android | iOS
Find the addresses you need or the best places nearby even when you’re offline with Yandex.Maps. Get detailed information on organizations and routes there on foot, by car, by bicycle or on public transport along with current traffic jam information. Search places and addresses even when you’re not connected with offline maps.
- Download maps to get driving directions and voice navigation when you are not connected to the internet.
- Save space on your device using more compact maps (Moscow, for example, only takes up 159 MB).
- Browse а selected region’s offline database of organizations with office hours, service information and other details.
- Get maps for over 2000 cities in Russia, Armenia, Belarus, Estonia, Georgia, Kazakhstan, Latvia, Turkey and Ukraine.
↓ 08 – Karta GPS | In-App Purchase | Android | iOS
Karta GPS is an offline map app with a solid interface for finding and interacting with relevant local spots. It offers driving directions with full voice, turn-by-turn details. Offline maps are provided by OpenStreetMap and enhanced by Karta Software Technologies, with guarantee of the latest data available and free updates forever.
- Beat the traffic – Our live traffic service finds faster routes and avoids traffic jams.
- Safety cameras alert – Know when you are approaching a speed-controlled zone.
- Enriched OpenStreetMap (OSM) maps – Free to download and use at any time.
- Automatic rerouting as traffic conditions change on the road.
↓ 09 – Magic Earth | 100% Free | Android | iOS
Magic Earth is a free turn-by-turn navigation app with downloadable maps and speed cameras alerts. It uses OpenStreetMap, it’s not just free, it also features high quality routes, lane information, speed limits and road signs, and crystal clear instructions.
Download maps to your phone and save big on mobile internet costs, navigate reliably even if you don’t have network coverage, or download only the region that you need. Or your entire country. Free and without giving up your privacy. With all the information stored on your iPhone, you don’t need to wait while map tiles download.
↓ 10 – 2GIS | Free [ With Ads ] | Android | iOS
2GIS provides 3D-maps of 180+ cities, contacts of 1.5 million companies, car routing and public transport routes and more! 2GIS is a complete and up-to-date directory of organizations with detailed cities’ maps. 2GIS provides verified information only. The app can operate offline even without a mobile data plan!
75 major metro areas available for download – UAE (Dubai), Cyprus (Lefkosia, Lemesos), Czech Republic (Prague), Chile (Santiago), Moscow, St. Petersburg, Novosibirsk, Abakan, Arkhangelsk, Astrakhan, Barnaul, Belgorod, Biysk, Blagoveshchensk, Bratsk, Bryansk, Cheboksary, Chelyabinsk, Chita, Gorno-Altaisk, Irkutsk, Ivanovo, Izhevsk, Kaliningrad, Kaluga, Kazan, Kemerovo, Khabarovsk, Kirov, Kostroma, Krasnodar, Krasnoyarsk, Kurgan, Kursk, Lipetsk, Magnitogorsk, Makhachkala, Naberezhnye Chelny, Nizhnevartovsk, Nizhny Novgorod, Nizhny Tagil, Novokuznetsk, Omsk, Orenburg, Penza, Perm, Prague, Rostov-on-Don, Ryazan, Samara, Saratov, Smolensk, Sochi, Stary Oskol, Stavropol, Sterlitamak, Surgut, Syktyvkar, Tolyatti, Tomsk, Tula, Tver, Tyumen, Ufa, Ulan-Ude, Ulyanovsk, Uralsk, Veliky Novgorod, Vladimir, Vladivostok, Volgograd, Vologda, Voronezh, Yakutsk, Yaroslavl, Yekaterinburg, Yoshkar Ola, Almaty, Astana, Bishkek, Dnepropetrovsk, Karaganda, Kiev, Odessa and Uralsk
↓ 11 – TomTom GO Mobile | Paid | Android | iOS
Somewhat expensive when there are so many free alternatives. TomTom GO Mobile is the navigation app with offline maps, and precise traffic and speed camera alerts. These help save time and money and let you drive new roads in over 150 countries. Whether you’re a commuter or a scenic driver TomTom GO Mobile makes you feel like you’re in the priority lane.
Connect to a wealth of information; both stored and online. Offline maps are stored locally, and help you save your data costs. When connected you can share your arrival time and benefit from the latest input from a community of millions.
- Offline navigation you can rely on – Maps are stored on your device, so you don’t need internet access or data roaming to plan a route. With coverage of more than 150 countries you can drive to endless destinations.
- Drive more relaxed with Speed Camera alerts – Get timely alerts for fixed and mobile speed cameras. Join our community of millions of drivers sharing speed camera locations in real-time.
- See buildings and landmarks in stunning 3D – With 3D Maps, you’ll always know exactly where you are.
- Insanely accurate traffic information – We’re passionate about traffic so you don’t need to be. Get highly accurate traffic information, in real-time.
↓ 12 – Garmin StreetPilot Onboard [ Discontinued ] | USD60 | iOS
Due to the failure of the Garmin Navigator App for both iOS and Android, Garmin rewrote the entire GPS app for smartphones. Due to the fragmentation of the Android OS system, it is exclusively for iOS only. Garmin StreetPilot Onboard is a one-time purchase that gives your iPhone® or iPad® the best GPS navigation — even when you don’t have cell coverage.
Maps are saved on your device, so you can look up addresses and millions of points of interest (POIs), such as gas stations, restaurants and ATMs, without wireless coverage. It’s like having a nüvi personal navigator on your Apple® device.
Designed exclusively for your iPhone or iPad, the StreetPilot Onboard app turns your Apple device into a premium GPS navigator with turn-by-turn, voice-prompted directions that speaks street names and automatically calculates a new route if you get off track.
- Install the latest maps for your purchased coverage area directly on your phone
- Enjoy GPS navigation even when there is no cell coverage available
- Get voice-prompted, turn-by-turn directions including street names
- Receive millions of preloaded POIs, including gas stations, restaurants and ATMs, along with Quick Search shortcuts to access your most common searches
- Place calls directly from search listings
- See 3-D buildings and landmarks
- Know the correct lane before it’s too late with lane guidance and photoReal™ junction view
- Receive integrated Speedwatch red-light and speed cameras (as available), including user-generated alerts
- Use via points to enable interim stops along a route
- View speed limits for most major roads with the ability to report speed limit changes or errors
- See traffic conditions with live photographic images of the road ahead with the optional photoLive traffic camera service
- Find nearest address, intersection, emergency services, including hospitals, police stations, gas stations and auto services with Where Am I? feature
- See exit services such as restaurants, gas stations and lodging available at exits along your route
- Create a route with multiple stops in advance with automatic or manual ordering of destinations
- Navigate to contacts in your address book
- Customize what appears on the moving map with configurable vehicle icons
- Configure display to show arrival time, time or distance to destination, direction of travel, elevation and more
- View route overview, turns list and turn-by-turn detail to help keep you on track
- See a trip log that shows you where you’ve been
- Enjoy super-fast map drawing and panning
- Receive continuous navigation during an active call
- Navigate in both portrait and landscape mode
- Access real-time traffic information, photoLive traffic cameras and fuel pricing as optional services
- View the current weather conditions and see a 5-day forecast for your current location or destination
How GPS Works?
The Global Positioning System, or GPS, is pretty amazing and chances are, it’s playing a much greater role in your life than you realize. Anthony explains how GPS works and tells you about some pretty cool upgrades coming soon.
Источник