- Android Current Location On Google Map Marker Example Tutorial
- Last Image
- Prerequisite For This Tutorial
- Step 1. Opening Maps Activity
- Step 2. Change gradle file
- Step 3. Writing GOOGLE API Key
- Step 4. Updating Manifest file
- Step 5. Final Changes
- Explanation of Maps Activity
- Google Maps Tutorials
- Download Source Code For Android Current Location On Google Map
- 5 thoughts on “Android Current Location On Google Map Marker Example Tutorial”
- Overview
- Introduction
- Concepts
- API overview
- Policies and Terms
- Данные о местоположении
- Примеры кода
- Работа с данными о местоположении
- Доступ к данным о местоположении
- Добавление разрешений в манифест приложения
- Запрос разрешений в среде выполнения
- Kotlin
- Слой «Мое местоположение»
- Kotlin
- Location API сервисов Google Play
Android Current Location On Google Map Marker Example Tutorial
We will develop Android Current Location On Google Map with marker in this example.
Now a days, number of people using google map is increasing significantly.
So most applications are using google map to simplify the user experience.
This tutorial will guide you to show current location on google map with marker in android studio.
First we will fetch the current latitude and longitude and then we will use them to show current location marker on google map.
For getting current location, we will use google’s FusedLocationAPI.
We will update the current location marker constantly on the google map with the current movement of the user.
Last Image
After successful implementation of all the steps, you should get the following output
I am living in Rajkot, India so red marker is there.
Prerequisite For This Tutorial
To go ahead with this example, you need to know some important details regarding google map and API Key.
You should create a project in google developer console and should get API Key first using above tutorial.
Do not create android studio project from above example. Just get your Google map API Key and after getting API Key, follow all the below steps.
Step 1. Opening Maps Activity
Create a new project in android studio. Give the name, directory, sdk level etc. details of new project.
After this, you will have a screen like the below image.
Step 2. Change gradle file
Now it is time to do some changes in build.gradle(Module: app) file
By default, you will have the below line in your build.gradle(Module: app) file because of Google Maps Activity
We also require following two lines here
- First line will help us to get the current location.
- Second line will fetch all the classes from dexter library to get the runtime permissions.
So final code for build.gradle(Module: app) file is as below
Step 3. Writing GOOGLE API Key
There is a file named google_maps_api.xml which is system generated.
- This google_maps_api.xml file is available at res->values directory.
- You need to write your Google API Key here in this file.
Code for this file is as following
- Add your API key in between Your API Key tags.
Step 4. Updating Manifest file
By default, you will have ACCESS_COARSE_LOCATION in your AndroidManifest.xml file
- Replace it with ACCESS_FINE_LOCATION because it is required to fetch more accurate current location.
Final code for AndroidManifest.xml
Step 5. Final Changes
Now we need to change the code of activity_maps.xml and MapsActivity.java file
Replace your existing code of activity_maps.xml with the following one
- Here I have taken four textviews which will represent the latitude and longitude values.
- One fragment is also there, which will open a google map.
- You will also some pre-written code in MapsActivity.java file.
Replace it with the below source code
Explanation of Maps Activity
Following snippet defines necessary variables.
- As you can see that GoogleMap, LocationRequest, LocationManager, Location etc. class’s objects are defined in the above code.
- long variables UPDATE_INTERVAL and FASTEST_INTERVAL defines the specific time amount.
Now consider the following source code
- First of all, compiler will check if the location permissions is granted or not. It will use requestSinglePermission() method for this purpose.
- requestSinglePermission() method will return a boolean variable (true or false) . If the user grants the location permission then it will return true otherwise false.
- If requestSinglePermission() return true, then compiler will start the process to fetch the current location and then it will create google map with the help of that current location.
Code snippet for requestSinglePermission() method is as below
- We have used Dexter library in this method. We will request for ACCESS_FINE_LOCATION in this method.
Now look at the below method
- This method is called when google map is ready to load.
- You need to provide location in terms of latitude and longitude in this method. Map will move it’s camera at this location.
- Marker is also added in this method only.
- onConnected(), onConnectionSuspended(), onConnectionFailed(), and onLocationChanged() methods are called by the compiler while fetching the current location.
Compiler will get the current latitude and longitude in onLocationChanged() method.
Source Code for onLocationChanged() method is as following
- Compiler will call this method every 20 seconds. After getting the location, compiler will again navigate the camera to the new location.
- Hence, Google map will be updated every 20 seconds as per the current movement of the user.
End for this tutorial. Keep navigating over DemoNuts to enhance your knowledge.
Google Maps Tutorials
Following are other useful tutorials on Google Map.
Download Source Code For Android Current Location On Google Map
5 thoughts on “Android Current Location On Google Map Marker Example Tutorial”
I’ve used your code and run it in my android studio. Everything is good, the app also runs in the emulator and asks for location, but I can not see a red marker for the location.
Emulator causes errors regarding locations, try in the real android device. It will definitely work.
Hello,
First, thanks for sharing your work. I tried this class and it works fine.
However, I have a question:
I added 2 buttons (1 for start and 1 for stop)
When I press either button, all gestures are suddenly disabled! Map seems frozen but update continue
and if I press the button to see the running apps and come back to the app, all gestures are usable again.
Could you explain how to keep gestures available all time please ?
Thanks for your answer.
Thanks for the code its perfectly working but in initial it doesn’t show the location why ? At initial launch i need to restart the app for it to get worked . Please update the code for finding route between two locations .
error: cannot find symbol class FragmentActivity
error: package android.support.annotation does not exist
error: package android.support.annotation does not exist
error: cannot find symbol class ActivityCompat
error: package android.support.v7.app does not exist
error: cannot find symbol class FragmentActivity
error: cannot find symbol class Nullable
error: cannot find symbol class NonNull
error: method does not override or implement a method from a supertype
error: cannot find symbol variable super
error: cannot find symbol method setContentView(int)
error: cannot find symbol method getSupportFragmentManager()
error: cannot find symbol method findViewById(int)
error: cannot find symbol method findViewById(int)
error: incompatible types: MapsActivity cannot be converted to Context
error: cannot find symbol method getSystemService(String)
error: method does not override or implement a method from a supertype
error: cannot find symbol variable ActivityCompat
error: cannot find symbol variable ActivityCompat
error: no suitable method found for makeText(MapsActivity,String,int)
method Toast.makeText(Context,CharSequence,int) is not applicable
(argument mismatch; MapsActivity cannot be converted to Context)
method Toast.makeText(Context,int,int) is not applicable
(argument mismatch; MapsActivity cannot be converted to Context)
error: method does not override or implement a method from a supertype
error: method does not override or implement a method from a supertype
error: method does not override or implement a method from a supertype
error: no suitable method found for makeText(MapsActivity,String,int)
method Toast.makeText(Context,CharSequence,int) is not applicable
(argument mismatch; MapsActivity cannot be converted to Context)
method Toast.makeText(Context,int,int) is not applicable
(argument mismatch; MapsActivity cannot be converted to Context)
error: cannot find symbol method getSupportFragmentManager()
error: cannot find symbol variable ActivityCompat
error: cannot find symbol variable ActivityCompat
error: no suitable method found for requestLocationUpdates(GoogleApiClient,LocationRequest,MapsActivity)
method FusedLocationProviderApi.requestLocationUpdates(GoogleApiClient,LocationRequest,LocationListener) is not applicable
(argument mismatch; MapsActivity cannot be converted to LocationListener)
method FusedLocationProviderApi.requestLocationUpdates(GoogleApiClient,LocationRequest,PendingIntent) is not applicable
(argument mismatch; MapsActivity cannot be converted to PendingIntent)
error: method does not override or implement a method from a supertype
error: cannot find symbol variable super
error: method does not override or implement a method from a supertype
error: cannot find symbol variable super
error: package AlertDialog does not exist
error: package AlertDialog does not exist
error: cannot find symbol method startActivity(Intent)
error: cannot find symbol method getSystemService(String)
error: no suitable method found for makeText(MapsActivity,String,int)
method Toast.makeText(Context,CharSequence,int) is not applicable
(argument mismatch; MapsActivity cannot be converted to Context)
method Toast.makeText(Context,int,int) is not applicable
(argument mismatch; MapsActivity cannot be converted to Context)
error: incompatible types: MapsActivity cannot be converted to Activity
uses or overrides a deprecated API.
i have all these error. please help. i follow exactly with the code given here. thank you
Источник
Overview
Introduction
The Places SDK for Android allows you to build location-aware apps that respond contextually to the local businesses and other places near the user’s device. This means you can build rich apps based on places that mean something to the user, to complement the straightforward geographic-based services offered by the Android location services.
Concepts
The following interfaces provide the primary entry points to the Places SDK for Android:
- Places provides programmatic access to Google’s database of local place and business information, as well as the device’s current place.
- Autocomplete provides pre-made widgets to return place predictions in response to user search queries.
A place is defined as a physical space that has a name. Another way of thinking about a place is that it’s anything you can find on a map. Examples include local businesses, points of interest, and geographic locations. In the API, a place is represented by the Place interface. It includes information such as the name of the place and its address, geographical location, place ID, phone number, place type, website URL, and more.
API overview
Help your customers explore where they are and what’s around them:
- Place Autocomplete automatically fills in the name and/or address of a place as users type.
- Current Place returns a list of places where the user’s device is last known to be located along with an indication of the relative likelihood for each place.
- Place Details return and display more detailed information about a place.
- Place Photos returns high-quality images of a place.
- Place IDs stores the unique ID for one or more places for retrieval of place information on demand.
Note: Google gathers anonymous usage statistics.
Policies and Terms
All applications that use the Places SDK for Android must adhere to the requirements described in the Google Maps Platform Terms of Service, Usage and Billing, and Displaying Attributions.
Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Источник
Данные о местоположении
В приложениях для мобильных устройств особенно важную роль играют данные о местоположении, применение которых способно обеспечить пользователю дополнительное удобство, где бы он ни находился.
Примеры кода
Хранилище ApiDemos на сайте GitHub содержит пример, который демонстрирует использование данных о местоположении на карте.
Java
- MyLocationDemoActivity: использование слоя «Мое местоположение», включая динамические разрешения.
- LocationSourceDemoActivity: использование собственного источника LocationSource .
- CurrentPlaceDetailsOnMap: определение текущего местоположения устройства Android и отображение сведений об организации или другом объекте, который там находится. Ознакомьтесь с руководством по отображению сведений о месте на карте.
Kotlin
- MyLocationDemoActivity: использование слоя «Мое местоположение», включая динамические разрешения.
- CurrentPlaceDetailsOnMap: определение текущего местоположения устройства Android и отображение сведений об организации или другом объекте, который там находится. Ознакомьтесь с руководством по отображению сведений о месте на карте.
Работа с данными о местоположении
Устройствам Android могут быть доступны данные о текущем местоположении (для их сбора используется комбинация нескольких технологий), о направлении и способе движения, а также о том, покинуло ли устройство геозону, т. е. пересекло ли оно заданную географическую границу. Работать с данными о местоположении можно несколькими способами в зависимости от задач конкретного приложения.
- Слой Мое местоположение представляет собой простой способ отобразить местонахождение устройства на карте. Он не возвращает никаких данных.
- Для всех программных запросов данных о местоположении рекомендуется использовать Location API сервисов Google Play.
- Интерфейс LocationSource позволяет использовать собственный источник данных о местоположении.
Доступ к данным о местоположении
Если приложению требуется доступ к данным о местоположении пользователя, вы должны запросить разрешение, добавив в приложение соответствующие настройки.
Android предлагает два разрешения на использование данных о местоположении: ACCESS_COARSE_LOCATION и ACCESS_FINE_LOCATION . От вашего выбора зависит, насколько точную информацию будет предоставлять API. Вам необходимо запросить только одно из разрешений на использование данных о местоположении Android в зависимости от требуемого уровня точности:
- android.permission.ACCESS_COARSE_LOCATION позволяет использовать точки доступа Wi-Fi и/или мобильные данные, чтобы определять приблизительное местоположение устройства. API предоставляет информацию о местоположении с точностью примерно до городского квартала.
- android.permission.ACCESS_FINE_LOCATION позволяет API максимально точно определять местоположение на основании информации, предоставляемой поставщиками данных о местоположении, включая глобальную систему позиционирования (GPS), сеть Wi-Fi и мобильные данные.
Добавление разрешений в манифест приложения
Добавьте одно из следующих разрешений в качестве дочернего для элемента в манифесте Android. Укажите разрешение для данных о приблизительном местоположении:
Или разрешение для данных о точном местоположении:
Запрос разрешений в среде выполнения
В Android 6.0 (Marshmallow) представлена новая модель работы с разрешениями, которая оптимизирует процесс установки и обновления приложений пользователями. Если ваше приложение предназначено для API уровня 23 или более позднего, вы можете использовать новую модель разрешений.
Если приложение поддерживает новую модель разрешений, а на устройстве используется Android 6.0 (Marshmallow) или более новая версия, пользователю не нужно предоставлять какие-либо разрешения при установке приложения или его обновлении. Пользователь увидит диалоговое окно с просьбой предоставить соответствующее разрешение.
Чтобы обеспечить удобство для пользователя, важно запрашивать доступ в контексте. Если эта информация необходима для работы приложения, запрашивайте разрешение при запуске. Для этого рекомендуется использовать экран приветствия или мастер с объяснением причины запроса.
Если доступ к данным о местоположении необходим приложению лишь для некоторых функций, то запрос следует показывать лишь при выполнении действия, требующего такого разрешения.
Приложение должно корректно продолжить работу, если пользователь откажется предоставить доступ. Например, если разрешение требуется лишь для определенной функции, приложение может просто отключить ее. Если же приложение неспособно работать без этих данных, в нем могут отключиться функциональные возможности. При этом следует проинформировать пользователя о том, что для дальнейшей работы нужен доступ к данным о местоположении.
В следующем примере кода проверка разрешения выполняется с использованием библиотеки поддержки перед включением слоя «Мое местоположение»: Затем результат запроса разрешения обрабатывается путем реализации ActivityCompat.OnRequestPermissionsResultCallback из библиотеки поддержки.
Kotlin
Слой «Мое местоположение»
Слой «Мое местоположение» и одноименная кнопка позволяют пользователям видеть свое актуальное местоположение на карте. Чтобы включить слой «Мое местоположение», вызовите метод mMap.setMyLocationEnabled() .
Простой пример использования слоя «Мое местоположение»:
Kotlin
Если включен слой «Мое местоположение», соответствующая кнопка отображается в правом верхнем углу экрана. При нажатии этой кнопки камера центрирует карту по текущему местоположению устройства, если оно известно. На карте местоположение обозначается маленькой синей точкой, если устройство неподвижно, или значком шеврона, если устройство находится в движении.
На скриншоте ниже вы можете увидеть кнопку «Мое местоположение» справа вверху и синюю точку в центре карты.
Чтобы предотвратить показ кнопки «Мое местоположение», вызовите UiSettings.setMyLocationButtonEnabled(false) .
Ваше приложение может реагировать на следующие события:
- Если пользователь нажимает кнопку «Мое местоположение», ваше приложение получает обратный вызов onMyLocationButtonClick() от прослушивателя GoogleMap.OnMyLocationButtonClickListener .
- Если пользователь нажимает на синюю точку «Мое местоположение», ваше приложение получает обратный вызов onMyLocationClick() от прослушивателя GoogleMap.OnMyLocationClickListener .
Важный пункт Условий использования
Обеспечивайте конфиденциальность пользователей,
информируйте их о том, что происходит в приложении.
Всегда сообщайте пользователям, как вы собираетесь применять их данные. Препятствуйте персональной идентификации пользователей по их данным. Перед применением данных о местоположении обязательно получите разрешение. Дайте пользователям возможность в любое время отозвать его.
Location API сервисов Google Play
Данные о местоположении в приложениях для Android лучше всего обрабатывать с помощью Location API сервисов Google Play. Он позволяет выполнять следующие задачи:
- определять местоположение устройства;
- отслеживать изменение местоположения с помощью прослушивателей;
- определять способ движения, если местоположение устройства меняется;
- создавать геозоны и отслеживать пересечение их границ.
Location API упрощает создание приложений, работающих с данными о текущем местоположении пользователя и эффективно расходующих ресурс аккумулятора устройства. Как и Maps SDK for Android, Location API распространяется как часть SDK сервисов Google Play. Дополнительную информацию вы можете найти в учебном материале об использовании в приложении данных о местоположении, а также в документации по Location API. Примеры кода содержатся в SDK сервисов Google Play.
Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Источник