I am trying to load google map in emulator for a given latitude and longitude.
Map is loading in the emulator but no marker is coming and same view is shown always.
i have followed the tutorial. Below is my code.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
double latitude = getIntent().getDoubleExtra("lat", 0);
double longitude = getIntent().getDoubleExtra("lng", 0);
Log.d("Zumbare","lat value : "+latitude);
Log.d("Zumbare","lng value : "+longitude);
LatLng position = new LatLng(latitude, longitude);
MarkerOptions options = new MarkerOptions();
options.position(position);
options.title("Position");
options.snippet("Latitude:"+latitude+",Longitude:"+longitude);
options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
SupportMapFragment fm = (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map);
GoogleMap googleMap = fm.getMap();
googleMap.setMyLocationEnabled(true);
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
googleMap.getUiSettings().setZoomControlsEnabled(true);
googleMap.getUiSettings().setCompassEnabled(true);
googleMap.addMarker(options);
CameraUpdate updatePosition = CameraUpdateFactory.newLatLng(position);
CameraUpdate updateZoom = CameraUpdateFactory.zoomBy(4);
googleMap.moveCamera(updatePosition);
googleMap.animateCamera(updateZoom);
}
Below is my manifest file.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.app.maptest.gmap" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<permission
android:name="com.app.maptest.gmap.MAPS_RECEIVE"
android:protectionLevel="signature"/>
<uses-permission android:name="com.app.maptest.gmap.MAPS_RECEIVE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-feature
android:glEsVersion="0x00020000"
android:required="true"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
</activity>
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="AIzaSyCInpkx8MO-lD4AMR4aUYns3tVvUMjIH1k" />
<activity
android:name=".MainActivity2"
android:label="#string/title_activity_main_activity2" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Can someone help me where the problem is..
Edit :
Yes, I am fetching lat lng of a city and logs are coming as..
1885-1885/com.app.maptest.gmap D/Zumbareļ¹ lat value : 16.506174
03-29 16:20:54.602 1885-1885/com.app.maptest.gmap D/Zumbareļ¹ lng value : 80.648015
Edit2:
I am using android studio and added the google play service in gradle file as below.
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:22.0.0'
compile 'com.google.android.gms:play-services:3.1.36'
}
I think the tutorial that you followed is outdated. play-services now is 6.5.87.
Please try to follow this step by step, you will finally get a map on your phone.
MainAcitivity, sample code:
public class MainActivity extends Activity {
private static LatLng goodLatLng = new LatLng(37, -120);
private GoogleMap googleMap;
private EditText et_address, et_finalAddress;
LatLng addressPos, finalAddressPos;
Marker addressMarker;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_address = (EditText) findViewById(R.id.addressEditText);
et_finalAddress = (EditText) findViewById(R.id.finalAddressEditText);
// Initial Map
try {
if (googleMap == null) {
googleMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
}
} catch (Exception e) {
e.printStackTrace();
}
googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
// Put a dot on my current location
googleMap.setMyLocationEnabled(true);
googleMap.setIndoorEnabled(true);
googleMap.setTrafficEnabled(true);
// 3D building
googleMap.setBuildingsEnabled(true);
// Get zoom button
googleMap.getUiSettings().setZoomControlsEnabled(true);
Marker marker = googleMap.addMarker(new MarkerOptions()
.position(goodLatLng)
.title("Hello"));
}
For more details, please refer to my github here.
Related
I want to show user location as per address submitted by him. For that i am using Geocoder. But i got following error.
10-17 18:21:02.734 1914-1934/com.example.googlemapdemo E/GMPM: getGoogleAppId failed with status: 10
10-17 18:21:02.735 1914-1934/com.example.googlemapdemo E/GMPM: Uploading is not possible. App measurement disabled
I have get google api key by following all steps. Here is my code
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.google.android.gms:play-services:8.1.0'
compile 'com.android.support:appcompat-v7:23.0.1'
compile 'com.android.support:design:23.0.1'
}
MainActivity.java
Geocoder geocoder = new Geocoder(getApplicationContext());
String result=null;
try {
List addressList = geocoder.getFromLocationName(address.getText().toString(),1);
if(addressList!=null && addressList.size() > 0) {
Address address = (Address) addressList.get(0);
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria,true);
double lat = address.getLatitude();
double longti = address.getLongitude();
Log.e("lat..long","lat...long"+lat+"....."+longti);
Intent intent = new Intent(MainActivity.this, MapsActivity.class);
intent.putExtra("Lat",lat);
intent.putExtra("Long",longti);
startActivity(intent);
}
} catch (IOException e) {
e.printStackTrace();
}
map.xml
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:map="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/map"
tools:context="com.example.googlemapdemo.MapsActivity"
android:name="com.google.android.gms.maps.SupportMapFragment"/>
MapActivity
package com.example.googlemapdemo;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
private double lat, longt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
lat = getIntent().getIntExtra("Lat",0);
longt = getIntent().getIntExtra("Long",0);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
/**
* Manipulates the map once available. This callback is triggered when the map is ready to be
* used. This is where we can add markers or lines, add listeners or move the camera. In this
* case, we just add a marker near Sydney, Australia. If Google Play services is not installed
* on the device, the user will be prompted to install it inside the SupportMapFragment. This
* method will only be triggered once the user has installed Google Play services and returned
* to the app.
*/
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(lat,longt);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
}
I also have added all permisions and api key to menifest
AndroidMenifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.googlemapdemo" >
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<permission
android:name="package.name.permission.MAPS_RECEIVE"
android:protectionLevel="signature" />
<uses-feature
android:glEsVersion="0x00020000"
android:required="true" />
<uses-library android:name="com.google.android.maps" />
<uses-permission android:name="package.name.permission.MAPS_RECEIVE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!--
The API key for Google Maps-based APIs is defined as a string resource.
(See the file "res/values/google_maps_api.xml").
Note that the API key is linked to the encryption key used to sign the APK.
You need a different API key for each encryption key, including the release key that is used to
sign the APK for publishing.
You can define the keys for the debug and release targets in src/debug/ and src/release/.
-->
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="#string/google_maps_key" />
<activity
android:name=".MapsActivity"
android:label="#string/title_activity_maps" >
</activity>
</application>
</manifest>
You need to add the package name and SHA certificate fingerprint on the developers console, under your key. Have you done that?
You need to add map key to show googlemap on your application.I didn't see it in the manifest file,i see only key for using GeoCoder
Try after adding your google map key. Example is shown below
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="AIxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" />
Try this, it may help you:
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> addresses = null;
try {
addresses = geocoder.getFromLocationName("Location String", 1);
} catch (IOException e) {
e.printStackTrace();
}
Address address = addresses.get(0);
if(addresses.size() > 0) {
double latitude = addresses.get(0).getLatitude();
double longitude = addresses.get(0).getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
mMap.addMarker(new MarkerOptions().position(latLng));
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(10));
}
Hi I want the user to be able to find their location on Google Maps v2. Something is happening when I click the location button on the map because a little satellite thing with beams coming off of it appears at the top of my phone. Can anyone help with this problem?
Also as a side question is there any way of adding directions or distance to a defined location too?
MapsActivity.java:
package com.example.softwaresearchapp;
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.Toast;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapsActivity extends Activity {
// Google Map
private GoogleMap googleMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.maps);
try {
// Loading map
initilizeMap();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* function to load map. If map is not created it will create it for you
* */
private void initilizeMap() {
if (googleMap == null) {
googleMap = ((MapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap();
// check if map is created successfully or not
if (googleMap == null) {
Toast.makeText(getApplicationContext(),
"Sorry! unable to create maps", Toast.LENGTH_SHORT)
.show();
}
}
googleMap.setMyLocationEnabled(true); // false to disable
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
googleMap.getUiSettings().setCompassEnabled(true);
googleMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
googleMap.addMarker(new MarkerOptions()
.position(new LatLng(52.911927, -1.187923))
.title("Nottingham Trent University - Clifton Campus"));
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
//googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
//googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
//googleMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
//googleMap.setMapType(GoogleMap.MAP_TYPE_NONE);
}
#Override
protected void onResume() {
super.onResume();
initilizeMap();
}
}
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.softwaresearchapp"
android:versionCode="1"
android:versionName="1.0" >
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-sdk android:minSdkVersion="11" android:targetSdkVersion="17" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/Theme.AppCompat.Light">
<activity
android:name="com.example.softwaresearchapp.MainActivity"
android:label="#string/app_name">
<meta-data
android:name="android.app.default_searchable"
android:value=".SearchResultsActivity" />
</activity>
<!-- Search results activity -->
<activity android:name="com.example.softwaresearchapp.SearchResultsActivity"
android:parentActivityName="com.example.softwaresearchapp.MainActivity" >
<intent-filter>
<action android:name="android.intent.action.SEARCH" />
</intent-filter>
<meta-data
android:name="android.app.searchable"
android:resource="#xml/searchable" />
</activity>
<activity android:name ="com.example.softwaresearchapp.MapsActivity"/>
<activity android:name ="com.example.softwaresearchapp.ABActivity"/>
<activity android:name="com.example.softwaresearchapp.SoftwareSearchActivity"/>
<activity android:name="com.example.softwaresearchapp.SplashActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="AIzaSyAyPwV_djsaafTUYCjEc_QyUgjnSdnriwg"/>
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
</application>
</manifest>
From the docs:
Make a marker draggable
You can reposition a marker once its been added to the map so long as its draggable property is set to true. Long press the marker to enable dragging. When you take your finger off the screen, the marker will remain in that position.
Markers are not draggable by default. You must explicitly set the marker to be draggable either with MarkerOptions.draggable(boolean) prior to adding it to the map, or Marker.setDraggable(boolean) once it has been added to the map. You can listen for drag events on the marker, as described in Marker drag events.
The below snippet adds a draggable marker at Perth, Australia.
static final LatLng PERTH = new LatLng(-31.90, 115.86);
Marker melbourne = mMap.addMarker(new MarkerOptions()
.position(PERTH)
.draggable(true));
More info here: https://developers.google.com/maps/documentation/android/marker?hl=nl#make_a_marker_draggable
Check this for the second question: Launching Google Maps Directions via an intent on Android
Here is how to do it:
// Acquire a reference to the system Location Manager
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
// Define a listener that responds to location updates
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
googleMap.addMarker(new MarkerOptions()
.position(new LatLng(location.getLatitude(), location.getLongitude()))
.title("Hello world"));
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
// Register the listener with the Location Manager to receive location updates
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
Also, be sure to add the correct permissions in your manifest:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
I am design a Google map in android , I have add Google map service lib,layout
<fragment
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:name="com.google.android.gms.maps.MapFragment"
/>
Main Activity is
public class MainActivity extends Activity {
private GoogleMap mMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
final LatLng CIU = new LatLng(35.21843892856462, 33.41662287712097);
Marker ciu = mMap.addMarker(new MarkerOptions().position(CIU).title("My Office"));
}
}
Manifest.xml
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<permission
android:name="maping.amit.com.permission.MAPS_RECEIVE"
android:protectionLevel="signature" />
<uses-permission android:name="maping.amit.com.permission.MAPS_RECEIVE"/>
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="my keys are there ....."/>
Providing the link follow where you can get the map
and for marking your location you this code
// latitude and longitude
double latitude = 17.385044;
double longitude = 78.486671;
// create marker
MarkerOptions marker = new MarkerOptions().position(new LatLng(latitude, longitude)).title("Hello Maps");
// Changing marker icon
marker.icon(BitmapDescriptorFactory.fromResource(R.drawable.my_marker_icon)));
// adding marker
googleMap.addMarker(marker);
How can I highlight an area/region on Google Maps v2 Android? I also have a list of geopoints of that particular region. It needs to highlight that region when you scroll to that region. It needs to fill color for nearby region to differentiate from each other so each region should have a different color.
You need to draw a polygon by selecting some points on map. Here is the code.
MainActivity.java
public class MainActivity extends FragmentActivity implements
OnMapClickListener,
OnMapLongClickListener,
OnMarkerClickListener {
private GoogleMap myMap;
Location myLocation;
boolean markerClicked;
PolygonOptions polygonOptions;
Polygon polygon;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentManager manager = getSupportFragmentManager();
SupportMapFragment mapFragment = (SupportMapFragment) manager
.findFragmentById(R.id.map);
myMap = mapFragment.getMap();
myMap.setMyLocationEnabled(true);
myMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
myMap.setOnMapClickListener(this);
myMap.setOnMapLongClickListener(this);
myMap.setOnMarkerClickListener(this);
markerClicked = false;
}
#Override
public void onMapLongClick(LatLng point)
{
myMap.addMarker(new MarkerOptions()
.position(point).title(point.toString()));
markerClicked = false;
}
#Override
public boolean onMarkerClick(Marker marker)
{
if(markerClicked)
{
if(polygon != null)
{
polygon.remove();
polygon = null;
}
polygonOptions.add(marker.getPosition());
polygonOptions.strokeColor(Color.BLACK);
polygonOptions.strokeWidth(5);
polygonOptions.fillColor(0x884d4d4d);
polygon = myMap.addPolygon(polygonOptions);
marker.remove();
}
else
{
if(polygon != null)
{
polygon.remove();
polygon = null;
}
polygonOptions = new PolygonOptions().add(marker.getPosition());
markerClicked = true;
marker.remove();
}
return true;
}
#Override
public void onMapClick(LatLng point)
{
Toast.makeText(getApplicationContext(),
"Long Press to select locations", Toast.LENGTH_LONG).show();
}
}
activity_main
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<fragment
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment" />
</RelativeLayout>
manfiest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.polygononmap"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<permission
android:name="com.example.googlemapwithsession.permission.MAPS_RECEIVE"
android:protectionLevel="signature" />
<uses-feature
android:glEsVersion="0x00020000"
android:required="true" />
<uses-permission android:name="google.map.ver2.permission.MAPS_RECEIVE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.polygononmap.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="your api key" />
</application>
</manifest>
now use long press to select points on map and click on marker will draw polygon accordingly.. I thing this will help.
http://www.youtube.com/watch?v=YEM90r9r9vI
for details https://developers.google.com/maps/documentation/android/reference/com/google/android/gms/maps/model/Polygon
You just draw a Polygon on your map and fill it with the color you need.
i am creating an app with a google map view and i want this app to detect the current location of the user and display the lat and long with a marker on the map but all i can do until now is the display of the google map and the detection of current location without any marker displayed and without any text appear to display the lat and long
i did not add a marker until now because i do not know where to put it in the code and what is the best practice to do that
can anyone help me ???
this is the code of the:
manifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="in.wptrafficanalyzer.locationgooglemapv2demo"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="16" />
<permission
android:name="in.wptrafficanalyzer.LocationGoogleMapV2Demo.permission.MAPS_RECEIVE"
android:protectionLevel="signature" />
<uses-permission android:name="in.wptrafficanalyzer.LocationGoogleMapV2Demo.permission.MAPS_RECEIVE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-feature
android:glEsVersion="0x00020000"
android:required="true" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="in.wptrafficanalyzer.locationgooglemapv2demo.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="API KEY" />
</application>
</manifest>
xml file
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<TextView
android:id="#+id/tv_location"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<fragment
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment" />
</RelativeLayout>
java file
package in.wptrafficanalyzer.locationgooglemapv2demo;
import android.app.Dialog;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.widget.TextView;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
public class MainActivity extends FragmentActivity implements LocationListener {
GoogleMap googleMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Getting Google Play availability status
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());
// Showing status
if(status!=ConnectionResult.SUCCESS){ // Google Play Services are not available
int requestCode = 10;
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
dialog.show();
}else { // Google Play Services are available
// Getting reference to the SupportMapFragment of activity_main.xml
SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
// Getting GoogleMap object from the fragment
googleMap = fm.getMap();
// Enabling MyLocation Layer of Google Map
googleMap.setMyLocationEnabled(true);
// Getting LocationManager object from System Service LOCATION_SERVICE
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// Creating a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Getting the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
// Getting Current Location
Location location = locationManager.getLastKnownLocation(provider);
if(location!=null){
onLocationChanged(location);
}
locationManager.requestLocationUpdates(provider, 20000, 0, this);
}
}
#Override
public void onLocationChanged(Location location) {
TextView tvLocation = (TextView) findViewById(R.id.tv_location);
// Getting latitude of the current location
double latitude = location.getLatitude();
// Getting longitude of the current location
double longitude = location.getLongitude();
// Creating a LatLng object for the current location
LatLng latLng = new LatLng(latitude, longitude);
// Showing the current location in Google Map
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
// Zoom in the Google Map
googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
// Setting latitude and longitude in the TextView tv_location
tvLocation.setText("Latitude:" + latitude + ", Longitude:"+ longitude );
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
First check the documentation here, it gives good indication on best strategies for getting user position.
Personally I usually start the map with a marker placed at the position retrivied with
Location lastKnownLocation = locationManager.getLastKnownLocation(locationProvider);
and then I start listening for position update and move the marker.
It also depend on how accurate position you need for the pourpose of your application, if you don't need really accurate position but the area is sufficient maybe you can just use thelastKnownLocation.
You can try something like this
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Getting Google Play availability status
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());
// Showing status
if(status!=ConnectionResult.SUCCESS){ // Google Play Services are not available
int requestCode = 10;
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
dialog.show();
}else { // Google Play Services are available
// Getting reference to the SupportMapFragment of activity_main.xml
SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
// Getting GoogleMap object from the fragment
googleMap = fm.getMap();
// Enabling MyLocation Layer of Google Map
googleMap.setMyLocationEnabled(true);
// Getting LocationManager object from System Service LOCATION_SERVICE
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// Creating a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Getting the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
// Getting Current Location
Location location = locationManager.getLastKnownLocation(provider);
LocationListener locationListener = new LocationListener() {
void onLocationChanged(Location location) {
// redraw the marker when get location update.
drawMarker(location);
}
if(location!=null){
//PLACE THE INITIAL MARKER
drawMarker(location);
}
locationManager.requestLocationUpdates(provider, 20000, 0, locationListener);
}
}
private void drawMarker(Location location){
// Remove any existing markers on the map
googleMap.clear();
LatLng currentPosition = new LatLng(location.getLatitude(),location.getLongitude());
googleMap.addMarker(new MarkerOptions()
.position(currentPosition)
.snippet("Lat:" + location.getLatitude() + "Lng:"+ location.getLongitude())
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE))
.title("ME"));
}
Also you don't need the Activity class to implements LocationListener, you can just define a listener and register it as I did above
P.S. I don't have an editor son my code can contain typo
Hope this helps, cheers
I just had the same problem, and found a way to do it using the Google Maps API:
private GoogleMap.OnMyLocationChangeListener myLocationChangeListener = new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location location) {
LatLng loc = new LatLng(location.getLatitude(), location.getLongitude());
mMarker = mMap.addMarker(new MarkerOptions().position(loc));
if(mMap != null){
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(loc, 16.0f));
}
}
};
and then set the listener for the map:
mMap.setOnMyLocationChangeListener(myLocationChangeListener);
This will get called when the map first finds the location.
No need for LocationService or LocationManager at all.
Full shortcut for defining the Google Map android v2 in android......
XML File :
<fragment
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
Menifest file :
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<!-- Map permission Starts -->
<permission
android:name="com.example.mapdemoapiv2.permission.MAPS_RECEIVE"
android:protectionLevel="signature" />
<uses-permission android:name="com.example.mapdemoapiv2.permission.MAPS_RECEIVE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-feature
android:glEsVersion="0x00020000"
android:required="true" />
<!-- Map permission Starts -->
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.mapdemoapiv2.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".MapDetail" >
</activity>
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="Your Key" />
<uses-library android:name="com.google.android.maps" />
</application>
Activity class :
public class MainActivity extends android.support.v4.app.FragmentActivity
{
GoogleMap googleMap;
MarkerOptions markerOptions;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setUpMapIfNeeded();
GetCurrentLocation();
}
private void setUpMapIfNeeded() {
if (googleMap == null) {
Log.e("", "Into null map");
googleMap = ((SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map)).getMap();
googleMap.setInfoWindowAdapter(new CustomInfoWindowAdapter(
MainActivity.this));
if (googleMap != null) {
Log.e("", "Into full map");
googleMap.setMapType(googleMap.MAP_TYPE_NORMAL);
googleMap.getUiSettings().setZoomControlsEnabled(false);
}
}
}
private void GetCurrentLocation() {
double[] d = getlocation();
Share.lat = d[0];
Share.lng = d[1];
googleMap
.addMarker(new MarkerOptions()
.position(new LatLng(Share.lat, Share.lng))
.title("Current Location")
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.dot_blue)));
googleMap
.animateCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(Share.lat, Share.lng), 5));
}
public double[] getlocation() {
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
List<String> providers = lm.getProviders(true);
Location l = null;
for (int i = 0; i < providers.size(); i++) {
l = lm.getLastKnownLocation(providers.get(i));
if (l != null)
break;
}
double[] gps = new double[2];
if (l != null) {
gps[0] = l.getLatitude();
gps[1] = l.getLongitude();
}
return gps;
}
It is better to use:
Location currentLocation =
LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
Documentation
easy like that:
after this -
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="Your Key" />
put this -
<meta-data android:name="com.google.android.gms.version" android:value="4030500" />