osmdroid get current user location - android

I am trying to implement OpenStreetMap using osmdroid. I successfully got the world map set to a particular set of geo co-ordinates. here is my code:
package com.example.re.osm;
//OSM MAP CODE
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import org.osmdroid.api.IMapController;
import org.osmdroid.config.Configuration;
import org.osmdroid.tileprovider.tilesource.TileSourceFactory;
import org.osmdroid.util.GeoPoint;
import org.osmdroid.views.MapView;
import org.osmdroid.views.overlay.mylocation.GpsMyLocationProvider;
import org.osmdroid.views.overlay.mylocation.MyLocationNewOverlay;
public class MainActivity extends Activity {
private MapView mMapView;
private MyLocationNewOverlay locationOverlay;
#Override public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Context ctx = getApplicationContext();
//important! set your user agent to prevent getting banned from the osm servers
Configuration.getInstance().load(ctx, PreferenceManager.getDefaultSharedPreferences(ctx));
setContentView(R.layout.activity_main);
MapView map = (MapView) findViewById(R.id.map);
map.setTileSource(TileSourceFactory.MAPNIK);
map.setBuiltInZoomControls(true);
map.setMultiTouchControls(true);
/*IMapController mapController = map.getController();
mapController.setZoom(9);
GeoPoint startPoint = new GeoPoint(48.8583, 2.2944);
mapController.setCenter(startPoint);*/
//add
locationOverlay = new MyLocationNewOverlay(map);
mOsmOverlays.add(locationOverlay);
}
public void onResume(){
super.onResume();
//this will refresh the osmdroid configuration on resuming.
//if you make changes to the configuration, use
//SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
//Configuration.getInstance().save(this, prefs);
Configuration.getInstance().load(this, PreferenceManager.getDefaultSharedPreferences(this));
//add
locationOverlay.enableMyLocation();
}
public void onPause(){
super.onPause();
//add
locationOverlay.disableMyLocation();
}
}
The current version of osmdroid (5.6.5) is used.
Manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.re.osm"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="10" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<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_WIFI_STATE" />
<application
android:icon="#drawable/ic_launcher"
android:label="OSM" >
<activity
android:name=".MainActivity"
android:label="OSM" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
How do I get the current user location in this?. Should I also use resource proxy?
Thanks.

You can use MyLocationNewOverlay
...
GeoPoint startPoint = new GeoPoint(48.8583, 2.2944);
mapController.setCenter(startPoint);
//add
GpsMyLocationProvider provider = new GpsMyLocationProvider(this);
provider.addLocationSource(LocationManager.NETWORK_PROVIDER);
locationOverlay = new MyLocationNewOverlay(map, provider);
locationOverlay.enableFollowLocation();
locationOverlay.runOnFirstFix(new Runnable() {
public void run() {
Log.d("MyTag", String.format("First location fix: %s", locationOverlay.getLastFix()));
}
});
map.getOverlayManager().add(locationOverlay);
In onResume method in the activity then add:
public void onResume(){
super.onResume();
//this will refresh the osmdroid configuration on resuming.
//if you make changes to the configuration, use
//SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
//Configuration.getInstance().save(this, prefs);
Configuration.getInstance().load(this, PreferenceManager.getDefaultSharedPreferences(this));
//add
locationOverlay.enableMyLocation();
}
And in onPause
public void onPause(){
super.onResume();
//add
locationOverlay.disableMyLocation();
}
Where locationOverlay is obviously a field typed as MyLocationNewOverlay.
For more details check documentation for the class. There's also an example in the sample application.

Related

Need a Android Studio/OSMDroid Guide for a school project

I'm currently developping an App in a school/exam purpose.
I'm using Android Studio 2.0 and an OPO with 5.1.1 on it and a Nexus 7 with 6.0.1 !
The goal is to display the location of the device on a map, and to trace a route passing by waypoints (cultural buildings).
I have no problem displaying the map (I'm able to center it on my city and with a good zoom level)
Now I want to display the current location of the device.
I encounter problems with permissions..
My manifest :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="alpha.testmap">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
// AUTORISATIONS
<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_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
My MainActivity.java:
package alpha.testmap;
import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import org.osmdroid.api.IMapController;
import org.osmdroid.tileprovider.tilesource.TileSourceFactory;
import org.osmdroid.util.GeoPoint;
import org.osmdroid.views.MapView;
public class MainActivity extends Activity {
private LocationManager mLocMgr;
#Override public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
//Can't find the class of this fonction --> REQUEST_LOCATION);
}else {
Location myLocation = LOCATION_SERVICE.FusedLocationApi.getLastLocaation(mGoogleApiClient);
}
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
//Can't find the class of this fonction --> REQUEST_LOCATION);
}
setContentView(R.layout.activity_main);
MapView map = (MapView) findViewById(R.id.map);
map.setTileSource(TileSourceFactory.MAPNIK);
//Adding zoom ability
map.setBuiltInZoomControls(true);
map.setMultiTouchControls(true);
//Create a default point
IMapController mapController = map.getController();
mapController.setZoom(16);
GeoPoint ptStart = new GeoPoint(47.215576, -1.549089);
mapController.setCenter(ptStart);
GeoPoint ptTourLu = new GeoPoint(47.21545, -1.54624);
//GPS
mLocMgr = (LocationManager) getSystemService(LOCATION_SERVICE);
mLocMgr.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 100, (LocationListener) this);
}
}
Your problem with permissions is due to changes brought to Android 6.0 that requires you to ask permission at runtime instead of requesting at install like before.
You can read more here, under the "Manifest" section.

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);

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
}

Android MapView Displays Black Screen

i am using google maps in my app. i am unable to get the map tiles. i just see a black screen. i have been struggling for 3 days now. i generate the map api key on my computer and i have added all the permissions in my menifest.xml file. but still unable to get map tiles.
ActivityMap.java
`
package com.example.locatometer;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import com.example.locatometer.utils.Tracker;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
public class ActivityMap extends MapActivity{
MapView mapView;
MapController controller;
Tracker tracker;
Handler locationHandler = new Handler();
GeoPoint mapPoint;
#Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.activity_current_location_on_map);
init();
}
private void init() {
mapView = (MapView) findViewById(R.id.map);
mapView.setBuiltInZoomControls(true);
mapView.setSatellite(true);
controller = mapView.getController();
}
#Override
protected void onResume() {
super.onResume();
}
#Override
protected void onPause() {
super.onPause();
}
#Override
protected boolean isRouteDisplayed() {
return false;
}
}
`
layout.xml
<?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" >
<com.google.android.maps.MapView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/map"
android:clickable="true"
android:apiKey="******************************" />
</LinearLayout>
manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.locatometer"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="5"
android:targetSdkVersion="10" />
<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_MOCK_LOCATION"/>
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/LocatometerTheme" android:debuggable="true">
<uses-library android:name="com.google.android.maps"/>
<activity
android:name="com.example.locatometer.ActivitySplash"
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.locatometer.ActivityMenu"></activity>
<activity android:name="com.example.locatometer.ActivityCurrentLocation"></activity>
<activity android:name="com.example.locatometer.ActivityMap"></activity>
</application>
</manifest>
It might not be related but i did this once when i was faced with a similar kind of issue. Under your application tag in manifest put
android:hardwareAccelerated="false"
Might not work but worth a try.

Android google maps showing greed lines

I have one google maps application it does not show the maps it only shows the lines
It does not show the mapview,and i also have the internet Connection
And it also genrate the following error
09-30 12:01:12.934: WARN/Resources(587): Converting to string:
TypedValue{t=0x12/d=0x0 a=2 r=0x7f050002}
09-30 12:01:13.094: WARN/GpsLocationProvider(59): Duplicate add listener for uid
10042
09-30 12:01:13.334: INFO/MapActivity(587): Handling network change
notification:CONNECTED
09-30 12:01:13.334: ERROR/MapActivity(587): Couldn't get connection factory client
Showmap.java
package de.vogella.android.locationapi.maps;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.RelativeLayout;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
public class ShowMap extends MapActivity {
private MapController mapController;
private MapView mapView;
private LocationManager locationManager;
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.main); // bind the layout to the activity
// create a map view
RelativeLayout linearLayout = (RelativeLayout) findViewById(R.id.mainlayout);
mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
mapView.setStreetView(true);
mapController = mapView.getController();
mapController.setZoom(14); // Zoon 1 is world view
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 13,
14, new GeoUpdateHandler());
}
#Override
protected boolean isRouteDisplayed() {
return false;
}
public class GeoUpdateHandler implements LocationListener {
#Override
public void onLocationChanged(Location location) {
int lat = (int) (location.getLatitude() * 1E6);
int lng = (int) (location.getLongitude() * 1E6);
GeoPoint point = new GeoPoint(lat, lng);
mapController.animateTo(point); // mapController.setCenter(point);
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
}
This is My mainfest
?xml version="1.0" encoding="utf-8"?>
<application android:icon="#drawable/icon" android:label="#string/app_name">
<uses-library android:name="com.google.android.maps" />
<activity android:name=".ShowMap"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<uses-library android:required="true" android:name="com.google.android.maps"></uses-library>
And main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/mainlayout"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<com.google.android.maps.MapView
android:id="#+id/mapview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:enabled="true"
android:clickable="true"
android:apiKey="0cHF-o_cvW1DEz3ocWAyybGqUsg8aUlwKMoyr4A"
/>
Do you have the required permissions in place in the AndroidManifest.xml? In an Android app that I've made for GPS + Maps I have the following:
<uses-permission android:name="android.permission.ACCESS_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_GPS" />
This is a problem with an API-Key.
Here you can do it.
You need to generate different one for each emulator, device etc. and for final release, and you need to merge them with an keystore you're using, what sux, but there is no different way :/.
Good luck!

Categories

Resources