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));
}
Related
I am simply creating a Map Project and executing this code. But there is getMap() error.
I have tried some example code from internet but there is also same error in getMap() function. The Code is :
private GoogleMap mMap;
static final LatLng TutorialsPoint = new LatLng(21 , 57);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
if (mMap == null) {
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
try {
if (mMap == null) {
mMap = ((MapFragment) getFragmentManager().
findFragmentById(R.id.map)).getMap();
//findFragmentById(R.id.map)).getMap();
}
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
Marker TP = mMap.addMarker(new MarkerOptions().
position(TutorialsPoint).title("TutorialsPoint"));
}
catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
This is my Android Manifest File.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.priya.finalproject">
<!--
The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
Google Maps Android API v2, but you must specify either coarse or fine
location permissions for the 'MyLocation' functionality.
-->
<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">
<!--
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.maps.v2.API_KEY"
android:value="AIzaSyCBp-ide4ue3DKt-tud4SdzwzR652OSnGY" />
<!-- <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">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
you should add marker into your map when onMapReady function is triggered and this happen when your map is ready to use (like adding marker etc).just initialize your map and call getMapAsync function like
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
use googleMap object to manipulate you map which is given to you inside onMapReady .
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.
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 creating a android which shows the user location with Google Maps through gps. when i run my program i have the following errors.
activity_main cannot be resolved or is not a field, displayMap cannot be resolved or is not a field
main cannot be resolved or is not a field. at first this error did not appear but after i save or clean my project, it appears
i have change the displayMap and save, clean my project in strings and xml file. but the error is still there.
Attribute "name" bound to namespace "http://schemas.android.com/apk/res/android" was already specified for element "meta-data" in my android manifest
Parser exception for /MyAppName/AndroidManifest.xml: Attribute "name" bound to namespace "http://schemas.android.com/apk/res/android" was already specified for element "meta-data". the resource for this is my ApplicationNameApp(my project name)
does that means i must change the "name" under meta data?
strings file
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">StudentHealthApp</string>
<string name="action_settings">Settings</string>
<string name="hello_world">Hello world!</string>
<string name="displayMap">Google Map Display</string>
</resources>
XML File
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<fragment
android:name="com.google.android.gms.maps.SupportMapFragment"
android:id="#+id/displayMap"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
Android Manifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.studenthealthapp"
android:versionCode="1"
android:versionName="1.0" >
<permission android:name="your.application.package.permission.MAPS_RECEIVE" android:protectionLevel="signature" />
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<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-features
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="com.example.studenthealthapp.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 value"
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
</application>
Main Java file
import android.R;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
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;
import com.google.android.gms.maps.model.MarkerOptions;
public class MainActivity extends FragmentActivity {
private GoogleMap googleMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setUpMapIfNeeded();
}
private void setUpMapIfNeeded() {
if(googleMap == null)
{
googleMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.displayMap)).getMap();
if(googleMap != null)
{
setUpMap();
}
}
}
private void setUpMap()
{
//Enable MyLocation Layer of Google Map
googleMap.setMyLocationEnabled(true);
//Get locationManager object from System Service LOCATION_SERVICE
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
//Create a criteria object to retrieve provider
Criteria criteria = new Criteria();
//Get the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
//Get current location
Location myLocation = locationManager.getLastKnownLocation(provider);
//set map type
googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
//Get latitude of the current location
double latitude = myLocation.getLatitude();
//Get longitude of the current location
double longitude = myLocation.getLongitude();
//Create a LatLng object for the current location
LatLng latLng = new LatLng(latitude, longitude);
//Show the current location in Google Map
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
//Zoom in the Google Map
googleMap.animateCamera(CameraUpdateFactory.zoomTo(20));
googleMap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title("You are here!"));
}
#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;
}}
i have added google play services as a project, google-play-services_lib appear as a seperate project folder then my application in eclipse. then i add to my libarary by Project -> Properties -> Android -> Library, Add -> google-play-services_lib
Change this
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="AIzaSyAZUoTQoHQwP25j0L_hTIUsXjxWmkFi3vg"
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
to
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="AIzaSyAZUoTQoHQwP25j0L_hTIUsXjxWmkFi3vg"/>
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
Remove
import android.R;
Instead you need
import com.example.studenthealthapp.R;
But if its in the same package then there is no need for import.
Also if you have errors in your resources files R.java will not be generated. So if any errors fix them and clean and build project.
remove import android.R;
and import your package name.R file
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext());
if (resultCode == ConnectionResult.SUCCESS){
Toast.makeText(getApplicationContext(),
"isGooglePlayServicesAvailable SUCCESS",
Toast.LENGTH_LONG).show();
}else{
GooglePlayServicesUtil.getErrorDialog(resultCode, this, RQS_GooglePlayServices);
}
}
I have made a very simple demo program for android map view (api v2) by referring the following link,But my program doesn't shows map.its not running.Please help me,My code is as below:
main.xml
<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:name="com.google.android.gms.maps.MapFragment"/>
main.java
package com.example.mymap;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.support.v4.app.FragmentActivity;
public class MainActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.mymap"
android:versionCode="1"
android:versionName="1.0" >
<uses-feature
android:glEsVersion="0x00020000"
android:required="true"/>
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<permission
android:name="com.example.mymap.permission.MAPS_RECEIVE"
android:protectionLevel="signature" />
<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="com.example.mymap.permission.MAPS_RECEIVE" />
<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" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.mymap.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="AIzaSyCuS-daQYgOZsmbIBYUTCl0P5tV0GTnjrI" />
</application>
</manifest>
Please try to use my running code.
Firstly import Google play service library project from /Android/android-sdk-linux/extras/google/google_play_services and after that create new project and write this code.
//Main Activity
package in.wptrafficanalyzer.multipleproximitymapv2;
import android.app.Dialog;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.widget.Toast;
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.GoogleMap.OnMapClickListener;
import com.google.android.gms.maps.GoogleMap.OnMapLongClickListener;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.CircleOptions;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MainActivity extends FragmentActivity {
GoogleMap googleMap;
LocationManager locationManager;
PendingIntent pendingIntent;
SharedPreferences sharedPreferences;
int locationCount = 0;
#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) getSystemService(LOCATION_SERVICE);
// Opening the sharedPreferences object
sharedPreferences = getSharedPreferences("location", 0);
// Getting number of locations already stored
locationCount = sharedPreferences.getInt("locationCount", 0);
// Getting stored zoom level if exists else return 0
String zoom = sharedPreferences.getString("zoom", "0");
// If locations are already saved
if (locationCount != 0) {
String lat = "";
String lng = "";
// Iterating through all the locations stored
for (int i = 0; i < locationCount; i++) {
// Getting the latitude of the i-th location
lat = sharedPreferences.getString("lat" + i, "0");
// Getting the longitude of the i-th location
lng = sharedPreferences.getString("lng" + i, "0");
// Drawing marker on the map
drawMarker(new LatLng(Double.parseDouble(lat),
Double.parseDouble(lng)));
// Drawing circle on the map
drawCircle(new LatLng(Double.parseDouble(lat),
Double.parseDouble(lng)));
}
// Moving CameraPosition to last clicked position
googleMap.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(
Double.parseDouble(lat), Double.parseDouble(lng))));
// Setting the zoom level in the map on last position is clicked
googleMap.animateCamera(CameraUpdateFactory.zoomTo(Float
.parseFloat(zoom)));
}
googleMap.setOnMapClickListener(new OnMapClickListener() {
public void onMapClick(LatLng point) {
// Incrementing location count
locationCount++;
// Drawing marker on the map
drawMarker(point);
// Drawing circle on the map
drawCircle(point);
// This intent will call the activity ProximityActivity
Intent proximityIntent = new Intent(
"in.wptrafficanalyzer.activity.proximity");
// Passing latitude to the PendingActivity
proximityIntent.putExtra("lat", point.latitude);
// Passing longitude to the PendingActivity
proximityIntent.putExtra("lng", point.longitude);
// Creating a pending intent which will be invoked by
// LocationManager when the specified region is
// entered or exited
pendingIntent = PendingIntent.getActivity(getBaseContext(),
0, proximityIntent, Intent.FLAG_ACTIVITY_NEW_TASK);
// Setting proximity alert
// The pending intent will be invoked when the device enters
// or exits the region 20 meters
// away from the marked point
// The -1 indicates that, the monitor will not be expired
locationManager.addProximityAlert(point.latitude,
point.longitude, 20, -1, pendingIntent);
/**
* Opening the editor object to write data to
* sharedPreferences
*/
SharedPreferences.Editor editor = sharedPreferences.edit();
// Storing the latitude for the i-th location
editor.putString(
"lat" + Integer.toString((locationCount - 1)),
Double.toString(point.latitude));
// Storing the longitude for the i-th location
editor.putString(
"lng" + Integer.toString((locationCount - 1)),
Double.toString(point.longitude));
// Storing the count of locations or marker count
editor.putInt("locationCount", locationCount);
/** Storing the zoom level to the shared preferences */
editor.putString("zoom",
Float.toString(googleMap.getCameraPosition().zoom));
/** Saving the values stored in the shared preferences */
editor.commit();
Toast.makeText(getBaseContext(),
"Proximity Alert is added", Toast.LENGTH_SHORT)
.show();
}
});
googleMap.setOnMapLongClickListener(new OnMapLongClickListener() {
public void onMapLongClick(LatLng point) {
Intent proximityIntent = new Intent(
"in.wptrafficanalyzer.activity.proximity");
pendingIntent = PendingIntent.getActivity(getBaseContext(),
0, proximityIntent, Intent.FLAG_ACTIVITY_NEW_TASK);
// Removing the proximity alert
locationManager.removeProximityAlert(pendingIntent);
// Removing the marker and circle from the Google Map
googleMap.clear();
// Opening the editor object to delete data from
// sharedPreferences
SharedPreferences.Editor editor = sharedPreferences.edit();
// Clearing the editor
editor.clear();
// Committing the changes
editor.commit();
Toast.makeText(getBaseContext(),
"Proximity Alert is removed", Toast.LENGTH_LONG)
.show();
}
});
}
}
private void drawCircle(LatLng point) {
// Instantiating CircleOptions to draw a circle around the marker
CircleOptions circleOptions = new CircleOptions();
// Specifying the center of the circle
circleOptions.center(point);
// Radius of the circle
circleOptions.radius(20);
// Border color of the circle
circleOptions.strokeColor(Color.BLACK);
// Fill color of the circle
circleOptions.fillColor(0x30ff0000);
// Border width of the circle
circleOptions.strokeWidth(2);
// Adding the circle to the GoogleMap
googleMap.addCircle(circleOptions);
}
private void drawMarker(LatLng point) {
// Creating an instance of MarkerOptions
MarkerOptions markerOptions = new MarkerOptions();
// Setting latitude and longitude for the marker
markerOptions.position(point);
// Adding InfoWindow title
markerOptions.title("Location Coordinates");
// Adding InfoWindow contents
markerOptions.snippet(Double.toString(point.latitude) + ","
+ Double.toString(point.longitude));
// Adding marker on the Google Map
googleMap.addMarker(markerOptions);
}
}
// activity_main
<fragment
android:id="#+id/map"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
class="com.google.android.gms.maps.SupportMapFragment" />
//Manifiest
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<permission
android:name="in.wptrafficanalyzer.multipleproximitymapv2.permission.MAPS_RECEIVE"
android:protectionLevel="signature" />
<uses-permission android:name="in.wptrafficanalyzer.multipleproximitymapv2.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" />
<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="in.wptrafficanalyzer.multipleproximitymapv2.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=".ProximityActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="in.wptrafficanalyzer.activity.proximity" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name=".NotificationView"
android:label="#string/app_name" >
<intent-filter>
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="AIzaSyD2fSGTakDlROXxr2IJeDH6f31b7BSc0F8" />
</application>
Add library to your AndroidManifest File:
<uses-library
android:name="com.google.android.maps"
android:required="true" />
Just check this:
package com.example.mymap;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.support.v4.app.FragmentActivity;
public class MainActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentManager myFM = .getSupportFragmentManager();
SupportMapFragment myMAPF = (SupportMapFragment) myFM
.findFragmentById(R.id.fragment1);
MAP = myMAPF.getMap();
MAP.setMyLocationEnabled(true);
MAP.setMapType(GoogleMap.MAP_TYPE_HYBRID);
MAP.setOnMapClickListener(new OnMapClickListener() {
#Override
public void onMapClick(LatLng point) {
// TODO Auto-generated method stub
MAP.addMarker(new MarkerOptions().position(point).title(
point.toString()));
Log.e("lat", "" + point);
}
});
}
}
Your xml file will be:
<fragment
android:id="#+id/fragment1"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_below="#+id/fragment1"
android:layout_centerHorizontal="true"
class="com.google.android.gms.maps.SupportMapFragment" />
And finally add libray in manifest file:
<uses-library
android:name="com.google.android.maps"
android:required="true" />
You should use SupportFragment Your min sdk is 8.
<fragment
class="com.google.android.gms.maps.SupportMapFragment"
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
Your activity must extend FragmentActivity
Import
import android.support.v4.app.FragmentActivity;
import com.google.android.gms.maps.SupportMapFragment;
Edit:
From your comments you say there is a error #
import com.google.android.gms.maps.SupportMapFragment;
So i guess you have not referenced google play services library project properly.
Download the Google Play services. Goto Windows. Goto Android Sdk Manager. Choose Google play services under extras.
Copy the google-play services_lib library project to your workspace. The library project can be found under the following path.
<android-sdk-folder>/extras/google/google_play_services/libproject/google-play-services_lib library project .
Import the library project to your eclipse
Click File > Import, select Android > Existing Android Code into Workspace, and browse the workspace import the library project. You can check if it is library project. Right click on the library project. Goto properties. Click Android on the left panel. You will see Is Library checked.
Try this.
In your xml file
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment"/>
In the java file
public class MapExampleActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map_example);
//setUpMap
}