Google maps fails to open in second activity - android

I'm making an application and ran into a problem.
I made separately app for google maps and it worked perfect, and I made second app in which I have listview, and by clicking on item in listview, another activity starts where google maps with different marks opens.
So I manage to get another activity running after clicking on separate objects in listview, so I modified that objects .xml and .java file on same principle as I did in my google maps app but somehow it doesn't works.
Main_Activity
package com.example.e_idem;
import android.os.Bundle;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.Gravity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends ListActivity {
String [] usluga = {
"Frizerski salon",
"Kafić",
"Vodoinstalater",
"Bravar",
"Ljekarna",
"Pekara",
"Autoservis",
"Dućan",
"Knjižnica",
"Papirnica",
"Željezara",
"Smartshop",
"Servis bicikla"
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Odaberite uslugu koju tražite.")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
AlertDialog alert = builder.create();
alert.show();
TextView messageView = (TextView)alert.findViewById(android.R.id.message);
messageView.setGravity(Gravity.CENTER);
setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, usluga));
}
public void onListItemClick(ListView parent, View view, int position,long id)
{
Toast.makeText(this, "Odabrali ste uslugu : "+usluga[position], Toast.LENGTH_LONG).show();
switch( position )
{
case 0: Intent activity_frizerski_salon = new Intent(this, FrizerskiSalon.class);
startActivity(activity_frizerski_salon);
break;
case 1: Intent activity_kafic = new Intent(this, Kafic.class);
startActivity(activity_kafic);
break;
case 2: Intent activity_vodoinstalater= new Intent(this, Vodoinstalater.class);
startActivity(activity_vodoinstalater);
break;
}
}
}
Activity I call in Main_Activity for clicking an object in listview
package com.example.e_idem;
import com.google.android.gms.maps.*;
import com.google.android.gms.maps.model.*;
import android.app.Activity;
import android.app.ListActivity;
import android.os.Bundle;
public class FrizerskiSalon extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_frizerski_salon);
// Get a handle to the Map Fragment
GoogleMap map = ((MapFragment) getFragmentManager()
.findFragmentById(R.id.fmap)).getMap();
LatLng vz = new LatLng(46.305746, 16.336606);
map.setMyLocationEnabled(true);
map.moveCamera(CameraUpdateFactory.newLatLngZoom(vz, 13));
map.addMarker(new MarkerOptions()
.title("Varaždin")
.snippet("Barokni grad")
.position(vz));
map.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.fromResource(R.drawable.flag_red))
.anchor(0.0f, 1.0f) // Anchors the marker on the bottom left
.position(new LatLng(46.300274, 16.330769)));
map.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.fromResource(R.drawable.flag_red))
.anchor(0.0f, 1.0f) // Anchors the marker on the bottom left
.position(new LatLng(46.306274, 16.300769)));
map.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.fromResource(R.drawable.flag_red))
.anchor(0.0f, 1.0f) // Anchors the marker on the bottom left
.position(new LatLng(46.306974, 16.303169)));
map.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.fromResource(R.drawable.flag_red))
.anchor(0.0f, 1.0f) // Anchors the marker on the bottom left
.position(new LatLng(46.302874, 16.400710)));
}
}
Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.e_idem"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="14" />
<permission
android:name="com.example.e_idem.permission.MAPS_RECEIVE"
android:protectionLevel="signature" />
<uses-permission android:name="com.example.e_idem.permission.MAPS_RECEIVE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_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-feature
android:glEsVersion="0x00020000"
android:required="true" />
<application
android:allowBackup="true"
android:icon="#drawable/house_flag"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.e_idem.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="com.example.e_idem.FrizerskiSalon"
android:label="#string/activity_frizerski_salon" >
</activity>
<activity
android:name="com.example.e_idem.Kafic"
android:label="#string/activity_kafic" >
</activity>
<activity
android:name="com.example.e_idem.Vodoinstalater"
android:label="#string/activity_vodoinstalater" >
</activity>
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="AIzaSyCKxxxxxxxxxxxxxxxxxxVfSY_9zxmU"/>
</application>
</manifest>
And my LogCat
http://paste.strictfp.com/39582

you need 2 meta-data entries in your manifest file:
1) map key
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="AIzaSyCKxxxxxxxxxxxxxxxxxxVfSY_9zxmU"/>
2) google play services version
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
You are missing the second one

Related

Genymotion just Doesnt launch GoogleMapsDemo Application-Eclipse.

I downloaded project of GoogleMapsDemo Application, it hasnt got errors on Eclipse. But in genymotion emulator it keeps saying unfortunately application cannot be launched.
Its MY Android manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="ca.sfu.cmpt276.bfraser"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="11"
android:targetSdkVersion="17" />
<permission
android:name="ca.sfu.cmpt276.bfraser.permission.MAPS_RECEIVE"
android:protectionLevel="signature"/>
<uses-permission android:name="ca.sfu.cmpt276.bfraser.permission.MAPS_RECEIVE"/>
<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"/>
<!-- The following two permissions are not required to use
Google Maps Android API v2, but are recommended. -->
<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" >
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="AIzaSyB1lm4b1b6DEwlROS1KA12Nhfa2IvbgS34"
/>
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version"/>
<activity
android:name="ca.sfu.cmpt276.bfraser.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>
</application>
And its my main_activity:
package ca.sfu.cmpt276.bfraser;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
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 MainActivity extends Activity {
private final LatLng LOCATION_BURNABY = new LatLng(49.27645, -122.917587);
private final LatLng LOCATION_SURRREY = new LatLng(49.187500, -122.849000);
private GoogleMap map;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
map.addMarker(new MarkerOptions().position(LOCATION_SURRREY).title("Find me 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;
}
public void onClick_City(View v) {
// CameraUpdate update = CameraUpdateFactory.newLatLng(LOCATION_BURNABY);
map.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
CameraUpdate update = CameraUpdateFactory.newLatLngZoom(LOCATION_BURNABY, 9);
map.animateCamera(update);
}
public void onClick_Burnaby(View v) {
map.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
CameraUpdate update = CameraUpdateFactory.newLatLngZoom(LOCATION_BURNABY, 14);
map.animateCamera(update);
}
public void onClick_Surrey(View v) {
map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
CameraUpdate update = CameraUpdateFactory.newLatLngZoom(LOCATION_SURRREY, 16);
map.animateCamera(update);
}
}
If you want to use Google services(like Google Maps), you need to first set up Google Play Services for Android, you may following the instruction form here. (Get your own API key, put in your AndroidManifest.xml, etc.)
I suggest you using a real device to test. If you want to use the Genymotion as a emulator, you need also get the google service first. For more details, please refer here.

How to find distance and travel route from current location to set marker

I am doing project on taxi fare calculation, my current location is displayed but i want to calculate distance and also show travel route from current location to other city using latitude..
please suggest n help...
Maps.java
package com.example.mainproject;
import java.util.List;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.widget.Toast;
import com.example.mainproject.R;
import com.google.android.gms.maps.CameraUpdate;
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.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class Maps extends FragmentActivity implements LocationListener {
// Google Map
private GoogleMap googleMap;
private LocationManager locationManager;
private static final long MIN_TIME = 400;
private static final float MIN_DISTANCE = 1000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.maps);
try {
// Loading map
initilizeMap();
// Changing map type
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);
// Showing / hiding your current location
googleMap.setMyLocationEnabled(true);
// Enable / Disable zooming controls
googleMap.getUiSettings().setZoomControlsEnabled(false);
// Enable / Disable my location button
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
// Enable / Disable Compass icon
googleMap.getUiSettings().setCompassEnabled(true);
// Enable / Disable Rotate gesture
googleMap.getUiSettings().setRotateGesturesEnabled(true);
// Enable / Disable zooming functionality
googleMap.getUiSettings().setZoomGesturesEnabled(true);
} catch (Exception e) {
e.printStackTrace();
}
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME,
MIN_DISTANCE, this); //You can also use LocationManager.GPS_PROVIDER and
LocationManager.PASSIVE_PROVIDER
}
#Override
public void onLocationChanged(Location location) {
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, 10);
googleMap.animateCamera(cameraUpdate);
locationManager.removeUpdates(this);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) { }
#Override
public void onProviderEnabled(String provider) { }
#Override
public void onProviderDisabled(String provider) { }
#Override
protected void onResume() {
super.onResume();
initilizeMap();
}
/**
* function to load map If map is not created it will create it for you
* */
private void initilizeMap() {
if (googleMap == null) {
googleMap = ((SupportMapFragment) getSupportFragmentManager().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();
}
}
}
}
map.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<fragment
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.mainproject"
android:versionCode="1"
android:versionName="1.0" >
<permission
android:name="com.example.mainproject.permission.MAPS_RECEIVE"
android:protectionLevel="signature" />
<uses-permission android:name="com.example.mainproject.permission.MAPS_RECEIVE" />
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<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.WRITE_EXTERNAL_STORAGE" />
<!-- Required to show current location -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<!-- Required OpenGL ES 2.0. for Maps V2 -->
<uses-feature
android:glEsVersion="0x00020000"
android:required="true" />
<!-- Requires OpenGL ES version 2 -->
<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" >
<uses-library android:name="com.google.android.maps" />
<activity
android:name="com.example.mainproject.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 class=".selectcity" android:label="selectcity"
android:name="com.example.mainproject.selectcity">
</activity>
<activity class=".About" android:label="About"
android:name="com.example.mainproject.About">
</activity>
<activity class=".entervalues" android:label="entervalues"
android:name="com.example.mainproject.entervalues">
</activity>
<activity class=".exit" android:label="exit" android:name="com.example.mainproject.exit">
</activity>
<activity class=".Maps" android:label="Maps" android:name="com.example.mainproject.Maps">
</activity>
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="AIza***************`enter code here`"/>
<meta-data android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
</application>
</manifest>
For getting direction and distance from Google you have to do following:
Write this code on direction button's click listener or anywhere from that you want to show direction and distance.
String uri = "http://maps.google.com/maps?saddr="
+ source_latitude + "," + source_longitude + "&daddr="
+ destination_latitude + ","
+ destination_longitude;
Intent intent = new Intent(android.content.Intent.ACTION_VIEW,
Uri.parse(uri));
intent.setClassName("com.google.android.apps.maps",
"com.google.android.maps.MapsActivity");
startActivity(intent);

android google maps project showing blank page with zoom in and zoom out buttons

I have created a project for google maps showing particular location but the output displays only a blank page with zoom in and out buttons. I am posting my code below.Please help me out.Thank you.
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.googlemapsv2"
android:versionCode="1"
android:versionName="1.0" >
<permission
android:name="com.example.googlemapsv2.permission.MAPS_RECEIVE"
android:protectionLevel="signature" />
<uses-permission android:name="com.example.googlemapsv2.permission.MAPS_RECEIVE" />
<uses-sdk
android:minSdkVersion="12"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<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.WRITE_EXTERNAL_STORAGE" />
<!-- Required to show current location -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<!-- Required OpenGL ES 2.0. for Maps V2 -->
<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="com.example.googlemapsv2.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.gms.version"
android:value="#integer/google_play_services_version" />
<!-- Google API Key -->
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="API KEY" />
</application>
</manifest>
activity_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"/>
MainActivity.java
package com.example.googlemapsv2;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import android.os.Build;
import android.app.Activity;
public class MainActivity extends Activity
{
// Google Map
GoogleMap googleMap;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
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();
double latitude = 19.990802;
double longitude = 72.742234;
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(19.990802, 72.742234)).zoom(16).build();
MarkerOptions marker = new MarkerOptions().position(
new LatLng(latitude, longitude)).title("Taj Mahal");
// googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
googleMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
// adding marker
googleMap.addMarker(marker);
// check if map is created successfully or not
if (googleMap == null) {
Toast.makeText(getApplicationContext(),
"Sorry! unable to create maps", Toast.LENGTH_SHORT)
.show();
}
}
}
}
Make sure your API key is generated with SHA-1 key + package name mentioned in the android manifest file not but your actual package.
i.e., SHA-1+com.example.googlemapsv2
If you are using eclipse go to Window->Preferences -> Android -> Build and generate a new api key for the SHA1 that you see in this window.
Put the new key in your manifest.
Probably you are using an api key for the apk. The keys are different between run/debug usage and apk deploy usage.

Google mapfragment not working in android

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
}

I have a mapview with icons for a specific location. How do I add mylocationoverlay?

I have been able to create a mapview from a tutorial online. That's working fine now.
However, I want to learn how to add my current location? I have been through several tutorials but can't get my head around it. Any ideas? This is the code i'll be working from.
MainActivity.java
package com.example.midlandtest;
import android.app.Activity;
import android.location.Location;
import android.os.Bundle;
import android.view.Menu;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
public class MainActivity extends Activity {
static final LatLng HAMBURG = new LatLng(53.28000, -7.49000);
static final LatLng KIEL = new LatLng(53.274823, -7.492655);
private GoogleMap map;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map))
.getMap();
Marker hamburg = map.addMarker(new MarkerOptions().position(HAMBURG)
.title("Tullamore"));
Marker kiel = map.addMarker(new MarkerOptions()
.position(KIEL)
.title("Midlands Regional Authority")
.snippet("Hey :-)")
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.ic_launcher)));
// Move the camera instantly to hamburg with a zoom of 15.
map.moveCamera(CameraUpdateFactory.newLatLngZoom(HAMBURG, 15));
// Zoom in, animating the camera.
map.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.midlandtest"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="15"
android:targetSdkVersion="17" />
<permission
android:name="com.example.midlandtest.permission.MAPS_RECEIVE"
android:protectionLevel="signature" />
<uses-feature
android:glEsVersion="0x00020000"
android:required="true" />
<uses-permission android:name="com.example.midlandtest.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" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.midlandtest.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="-" />
</application>
</manifest>
main.xml
<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.MapFragment" />
</RelativeLayout>
Call setMyLocationEnabled(true) on your GoogleMap.

Categories

Resources