I am new at Android. I have been trying from many days to make very
basic google map application but unable to complete it yet... :(
There are no errors in code, emulator running fine from terminal, Map
key also fine but still I am unable to see the map. When I run my
app only grid appears and map is not displayed. Here is the code, can
any body please help me.
public class HelloGoogleMaps extends MapActivity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
MapView mapView =(MapView)findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
}
protected boolean isRouteDisplayed(){
return false;
}
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<com.google.android.maps.MapView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/mapview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:clickable="true"
android:apiKey="0fyF-qSuCtdQinoUGoFbLxZoTx10Tm-YV6m6A8g"
/>
manifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.android.GoogleMaps"
android:versionCode="1"
android:versionName="1.0">
<uses-permission android:name="android.permission.INTERNET"/
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<application android:icon="#drawable/icon" android:label="#string/app_name">
<uses-library android:name="com.google.android.maps" />
<uses-permission android:name="android.permission.INTERNET"/>
<activity android:name=".HelloGoogleMaps"
android:label="#string/app_name"
android:theme="#android:style/Theme.NoTitleBar">
<!--<activity android:name=".HelloGoogleMaps"
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>
<uses-sdk android:minSdkVersion="4" />
</manifest>
Don't know where is anything wrong. I am using eclipse and android 1.6
try setting internet permission outside the application tag
**// Activty**
public class MapsActivity extends MapActivity {
private MapController mapController;
private MapView mapView;
private LocationManager locationManager;
private MyOverlays itemizedoverlay;
private MyLocationOverlay myLocationOverlay;
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.main); // bind the layout to the activity
// Configure the Map
mapView = (MapView) findViewById(R.id.map_container);
mapView.setBuiltInZoomControls(true);
// mapView.setSatellite(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, 0,
0, new GeoUpdateHandler());
myLocationOverlay = new MyLocationOverlay(this, mapView);
mapView.getOverlays().add(myLocationOverlay);
myLocationOverlay.runOnFirstFix(new Runnable() {
public void run() {
mapView.getController().animateTo(myLocationOverlay.getMyLocation());
}
});
Drawable drawable = this.getResources().getDrawable(R.drawable.map);
itemizedoverlay = new MyOverlays(this, drawable);
createMarker();
}
protected boolean isRouteDisplayed() {
return false;
}
public class GeoUpdateHandler implements LocationListener {
public void onLocationChanged(Location location) {
int lat = (int) (location.getLatitude() * 1E6);
int lng = (int) (location.getLongitude() * 1E6);
GeoPoint point = new GeoPoint(lat, lng);
createMarker();
mapController.animateTo(point); // mapController.setCenter(point);
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
private void createMarker() {
GeoPoint p = mapView.getMapCenter();
OverlayItem overlayitem = new OverlayItem(p, "", "");
itemizedoverlay.addOverlay(overlayitem);
if (itemizedoverlay.size() > 0) {
mapView.getOverlays().add(itemizedoverlay);
}
}
protected void onResume() {
super.onResume();
myLocationOverlay.enableMyLocation();
myLocationOverlay.enableCompass();
}
protected void onPause() {
super.onPause();
myLocationOverlay.disableMyLocation();
myLocationOverlay.disableCompass();
}
}
**//Class MyOvelays**
public class MyOverlays extends ItemizedOverlay<OverlayItem> {
private static int maxNum = 5;
private OverlayItem overlays[] = new OverlayItem[maxNum];
private int index = 0;
private boolean full = false;
private Context context;
private OverlayItem previousoverlay;
public MyOverlays(Context context, Drawable defaultMarker) {
super(boundCenterBottom(defaultMarker));
this.context = context;
}
#Override
protected OverlayItem createItem(int i) {
return overlays[i];
}
#Override
public int size() {
if (full) {
return overlays.length;
} else {
return index;
}
}
public void addOverlay(OverlayItem overlay) {
if (previousoverlay != null) {
if (index < maxNum) {
overlays[index] = previousoverlay;
} else {
index = 0;
full = true;
overlays[index] = previousoverlay;
}
index++;
populate();
}
this.previousoverlay = overlay;
}
protected boolean onTap(int index) {
OverlayItem overlayItem = overlays[index];
Builder builder = new AlertDialog.Builder(context);
builder.setMessage("This will end the activity");
builder.setCancelable(true);
builder.setPositiveButton("I agree", new OkOnClickListener());
builder.setNegativeButton("No, no", new CancelOnClickListener());
AlertDialog dialog = builder.create();
dialog.show();
return true;
};
private final class CancelOnClickListener implements
DialogInterface.OnClickListener {
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(context, "You clicked yes", Toast.LENGTH_LONG)
.show();
}
}
private final class OkOnClickListener implements
DialogInterface.OnClickListener {
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(context, "You clicked no", Toast.LENGTH_LONG).show();
}
}
}
//Main.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">
<com.google.android.maps.MapView
android:id="#+id/map_container"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:apiKey="0PYAmXmindXBuvCvIFhCUC3y0GNjJKuFJHclkVw"
android:clickable="true"
android:focusable="true"
android:keepScreenOn="true"
/>
</RelativeLayout>
//Android.mainifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.map"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="10" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<uses-library android:name="com.google.android.maps" />
<activity
android:name=".MapsActivity"
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>
</manifest>
Are you using the correct Google Maps key - if you use a debug key, the maps seem not to work.
You might have to regenerate the key without the --debug flag.
maybe this will help: Android MapView - tiles not loading with Debug API key
Common issues are that you're using the wrong emulator (ie not the Google APIs one), have the wrong imports, have the wrong API key, don't have permissions in manifest, don't have uses library etc
I wrote up a newbies guide on this, have a look
http://www.jameselsey.co.uk/blogs/techblog/android-how-to-display-a-map-the-easy-way/
I have recently been through all of these. I as well tried everything mentioned but all that worked is -
Make sure you are not a behind a proxy and remove any proxy settings you made on the emulator. There's a bug that Google Maps doesn't work on Android Emulators behind a proxy.
I think the problem is that you are using a wrong apk. You must use the apk generated by the emulator (eclipse in my case) and not the apk generated using the option "export". I think the problem is related to the key used to export the apk is not the same as the google maps api key. Try it.
PS: sorry for my bad English.
Related
I'm doing a university project, and i've to show user location in the OSM map, and markers with data from Retrofit API.
I'm not worried about api data right now, but with my map that isn't showing.
All i got is this:MainMap
The coordinates here are random.
My map activity:
public class MapaPrincipal extends AppCompatActivity implements LocationListener {
private MapView osm;
private MapController mc;
private LocationManager locationManager;
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mapa_principal);
osm = (MapView) findViewById(R.id.mapView);
osm.setTileSource(TileSourceFactory.MAPNIK);
osm.setBuiltInZoomControls(true);
osm.setMultiTouchControls(true);
mc = (MapController) osm.getController();
GeoPoint center = new GeoPoint(14.1, 19.2);
mc.setZoom(12);
mc.animateTo(center);
addMarker(center);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// Activity#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for Activity#requestPermissions for more details.
return;
}
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
public void addMarker(GeoPoint center){
Marker marker = new Marker(osm);
marker.setPosition(center);
marker.setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_BOTTOM);
osm.getOverlays().clear();
osm.getOverlays().add(marker);
osm.invalidate();
}
#Override
public void onLocationChanged(Location location) {
GeoPoint center = new GeoPoint(location.getLatitude(),location.getLongitude());
mc.animateTo(center);
addMarker(center);
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
#Override
protected void onDestroy() {
super.onDestroy();
if(locationManager!=null){
locationManager.removeUpdates(this);
}
}
}
My map layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
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"
android:orientation="vertical">
<org.osmdroid.views.MapView
android:id="#+id/mapView"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"/>
</LinearLayout>
Android Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="pt.ipp.estg.osm">
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<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="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<application
android:usesCleartextTraffic="true"
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SignUpActivity" />
<activity android:name=".MapaPrincipal" />
</application>
</manifest>
Can someone help me?
I am having some prolems with my google maps app. For now the app was only suppost to get my location em zoom in it, but is not working. My location aways ends in the top of the map. Here is my code:
MainActivity:
public class MainActivity extends Activity implements LocationListener {
private GoogleMap googleMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (isGooglePlayOk()) {
setContentView(R.layout.activity_main);
setMap();
googleMap.setMyLocationEnabled(true);
}
}
#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;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
case R.id.action_legalnotices:
startActivity(new Intent(this, LegalNoticeActivity.class));
return true;
default:
return false;
}
}
private boolean isGooglePlayOk() {
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (status == ConnectionResult.SUCCESS) {
return (true);
}
else {
((Dialog) GooglePlayServicesUtil.getErrorDialog(status, this, 10))
.show();
}
return (false);
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void setMap() {
if (googleMap == null) {
googleMap = ((MapFragment) getFragmentManager().findFragmentById(
R.main.map)).getMap();
if (googleMap != null) {
}
googleMap.setMyLocationEnabled(true);
LocationManager la = (LocationManager) getSystemService(LOCATION_SERVICE);
String provider = la.getBestProvider(new Criteria(), true);
Location loc = la.getLastKnownLocation(provider);
if (provider != null) {
onLocationChanged(loc);
}
googleMap.setOnMapLongClickListener(onLongClickMapSettiins());
}
}
private OnMapLongClickListener onLongClickMapSettiins() {
// TODO Auto-generated method stub
return new OnMapLongClickListener() {
#Override
public void onMapLongClick(LatLng point) {
Toast.makeText(getApplicationContext(), "OK",
Toast.LENGTH_SHORT).show();
}
};
}
#Override
public void onLocationChanged(Location location) {
LatLng latlong = new LatLng(location.getLatitude(),
location.getLongitude());
googleMap.setMyLocationEnabled(true);
CameraPosition cp = new CameraPosition.Builder().target(latlong)
.zoom(15).build();
googleMap.moveCamera(CameraUpdateFactory.newCameraPosition(cp));
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
activity_main:
<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+main/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:name="com.google.android.gms.maps.MapFragment"/>
Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.mapateste"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<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-feature
android:glEsVersion="0x00020000"
android:required="true" />
<!--
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" />
<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="(My Api is working fine)" />
<activity
android:name="com.example.mapateste.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.mapateste.LegalNoticeActivity"
android:label="#string/title_activity_legal_notice" >
</activity>
</application>
I can only test in my device. The map is working fine but i cannot get my position on the center of the screen right away only clicking at the mylocationbutton. Somebody can help me?
Just declare a point where you want to center your point.
LatLng cur_Latlng = new LatLng(21.0000, 78.0000);
gm.moveCamera(CameraUpdateFactory.newLatLng(cur_Latlng));
gm.animateCamera(CameraUpdateFactory.zoomTo(4));
the desired zoom level is in the range of 2.0 to 21.0.
// try this
#Override
public void onLocationChanged(Location location) {
LatLng latlong = new LatLng(location.getLatitude(),
location.getLongitude());
googleMap.animateCamera(CameraUpdateFactory.newLatLng(latlong));
googleMap.animateCamera(CameraUpdateFactory.zoomBy(15));
}
Your min sdk is 8. You should use SupportMapFragment. Your class must extend FragmentActivtiy
Check the line above developers guide heading in the below link
https://developers.google.com/maps/documentation/android/reference/com/google/android/gms/maps/MapFragment
<fragment
class="com.google.android.gms.maps.SupportMapFragment"
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
Use SupportMapFragment
SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
GoogleMap mMap = fm.getMap();
Make sure you have added support library
Also make sure you imported the below
import android.support.v4.app.FragmentActivity;
import com.google.android.gms.maps.SupportMapFragment
To zoom
CameraUpdate update = CameraUpdateFactory.newLatLngZoom(latlong,20);
googleMap.moveCamera(update);
This is working Current Location with zoom for Google Map V2
double lat= location.getLatitude();
double lng = location.getLongitude();
LatLng ll = new LatLng(lat, lng);
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(ll, 20));
Note that the My Location layer does not return any data. If you wish to access location data programmatically, use the Location API.
In your MainActivity (onCreate Method)
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(MainActivity.this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
On method onMapReady
#Override
public void onMapReady(GoogleMap googleMap) {
GoogleMap mMap = googleMap;
// Set blue point on the map at your cuurent location
mMap.setMyLocationEnabled(true);
// Show zoon controls on the map layer
mMap.getUiSettings().setZoomControlsEnabled(true);
//Show My Location Button on the map
mMap.getUiSettings().setMyLocationButtonEnabled(true);
}
on method onConnected
#Override
public void onConnected(Bundle bundle) {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (mLastLocation != null) {
LocationListener.latlonInit= new LatLng(mLastLocation.getLatitude(),mLastLocation.getLongitude());
CameraPosition target = CameraPosition.builder().tilt(66.0f).target(LocationListener.latlonInit)
.zoom(MainActivity.ZOOM).build();
mMap.moveCamera(CameraUpdateFactory.newCameraPosition(target));
}
}
You class should extend Fragment Activity
public class MainActivity extends FragmentActivity {
//assign any arbitrary value to GPS_ERRODIALOG_REQUEST
private static final int GPS_ERRORDIALOG_REQUEST = 9001;
GoogleMap googlemap;
}
for Google Service Ok method I would do Following:
public boolean isGooglePlayOk(){
int isAvailable = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (isAvailable == ConnectionResult.SUCCESS) {
return true;
}
else if(GooglePlayServicesUtil.isUserRecoverableError(isAvailable)){
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(isAvailable, this, GPS_ERRORDIALOG_REQUEST);
dialog.show();
}
else {
Toast.makeText(this, "Can't connect to Goolge Play", Toast.LENGTH_SHORT).show();
}
return false;
}
In the .xml file, when you declare the fragment, you need to support Map Fragment since your min skd is 8:
<fragment
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:maps="http://schemas.android.com/apk/res-auto"
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
activity_map.xml is for displaying map if condition is true for setMap else go to you regular activity_main.xml.
public class MainActivity extends FragmentActivity {
GoogleMap mMap;
if (isGooglePlayOk()) {
setContentView(R.layout.activity_map);
if (setMap()) {
mMap.setMyLocationEnabled(true);
}
else {
//your code
}
}
else {
setContentView(R.layout.activity_main);
}
method for setMap:
private boolean setMap() {
if (mMap == null) {
SupportMapFragment mapFrag =
(SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mMap = mapFrag.getMap();
}
return (mMap != null);
}
If you want to automatically zoom to some point in google maps v2 u can do like this
private float previousZoomLevel = 13.00f;
LatLng zoomPoint = new LatLng(12.977286, 77.632720);
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(zoomPoint,previousZoomLevel));
here previousZoomLevel is level of zoom
Im not sure whats wrong but Im trying to get my google maps fragment to zoom in to a particular location on start. For some reason, it is not working and still zooms in to africa by default. Here is my code.
public class OutbreakMap extends Activity implements LocationListener {
double lat=50;
double longi=50;
private LocationManager locationManager;
private String provider;
private MapFragment mMapFragment;
private GoogleMap googleMap;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.location);
// Get the location manager
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
boolean enabled = service.isProviderEnabled(LocationManager.GPS_PROVIDER);
// Check if enabled and if not send user to the GSP settings
// Better solution would be to display a dialog and suggesting to
// go to the settings
if (!enabled) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
// set title
alertDialogBuilder.setTitle("Turn On Your GPS");
// set dialog message
alertDialogBuilder
.setMessage("Please turn on your GPS to track sickness in your area!")
.setCancelable(false)
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, close
// current activity
OutbreakMap.this.finish();
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
})
.setNegativeButton("No",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
// Define the criteria how to select the locatioin provider -> use
// default
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
// Initialize the location fields
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
onLocationChanged(location);
} else {
Toast.makeText(getApplicationContext(),"Location not found",Toast.LENGTH_SHORT);
}
mMapFragment = MapFragment.newInstance();
FragmentTransaction fragmentTransaction =
getFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.map, mMapFragment);
fragmentTransaction.commit();
googleMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map))
.getMap();
setUpMapIfNeeded();
googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
if(location != null) {
lat=location.getLatitude();
longi=location.getLongitude();
}
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(lat,longi)) // Sets the center of the map to Mountain View
.zoom(17) // Sets the zoom
// Sets the tilt of the camera to 30 degrees
.build(); // Creates a CameraPosition from the builder
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
UiSettings uiSettings=googleMap.getUiSettings();
uiSettings.setAllGesturesEnabled(false);
// Initialize the location fields
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
onLocationChanged(location);
} else {
Toast.makeText(getApplicationContext(),"Couldn't Find Location",Toast.LENGTH_SHORT);
}
ParseGeoPoint userLoc= new ParseGeoPoint(lat,longi);
ParseQuery query= new ParseQuery("Outbreak");
query.whereWithinMiles("location",userLoc,1);
query.findInBackground(new FindCallback() {
public void done(List<ParseObject> objects, ParseException e) {
if (e == null) {
GetOutbreaks.getOutBreaksNearMe(googleMap,lat,longi,objects);
Toast.makeText(getApplicationContext(),"Recieved Outbreak Data",Toast.LENGTH_SHORT);
} else {
e.printStackTrace();
Toast.makeText(getApplicationContext(),"Could Not Download Data",Toast.LENGTH_SHORT);
}
}
});
// moveToPrescription();
// moveToPrescription();
}
/* Request updates at startup */
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
/* Remove the locationlistener updates when Activity is paused */
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
#Override
public void onLocationChanged(Location location) {
int lat = (int) (location.getLatitude());
int lng = (int) (location.getLongitude());
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(this, "Enabled new provider " + provider,
Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(this, "Disabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
public void moveToPrescription(){
Intent intent = new Intent(this,Prescription.class);
startActivity(intent);
}
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (googleMap == null) {
googleMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map))
.getMap();
// Check if we were successful in obtaining the map.
if (googleMap != null) {
// The Map is verified. It is now safe to manipulate the map.
}
}
}
}
Also, here is my xml layout for the map fragment activity
<?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 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"/>
</LinearLayout>
And my Android manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.parse.starter"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="4" android:targetSdkVersion="15"/>
<permission
android:name="com.example.mapdemo.permission.MAPS_RECEIVE"
android:protectionLevel="signature"/>
<uses-permission android:name="com.example.mapdemo.permission.MAPS_RECEIVE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.INTERNET" />
<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-permission android:name="android.permission.WAKE_LOCK"/>
<application
android:name="ParseApplication"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:name=".ParseStarterProjectActivity"
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=".Register"/>
<activity android:name=".Login"/>
<activity android:name=".Home"/>
<activity android:name=".OutbreakMap"/>
<activity android:name=".Prescription"/>
<activity android:name=".MyPrescriptions"/>
<receiver android:name=".AlarmManagerBroadcastReceiver"></receiver>
<uses-library android:name="com.google.android.maps"/>
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="My Maps API Key is Here"/>
</application>
<uses-feature android:glEsVersion="0x00020000" android:required="true" />
</manifest>
The LogCat is not showing any errors. Thanks for the help!
You are adding second SupportMapFragment in code on top of Fragment having GoogleMap you interact with. Just remove unnecessary code.
Use SupportMapFragment
<fragment
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
/>
GoogleMap gm;
gm = ((SupportMapFragment(getSupportFragmentManager().findFragmentById(R.id.map))).getMap();
Comment out the following lines of code
mMapFragment = MapFragment.newInstance();
FragmentTransaction fragmentTransaction =
getFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.map, mMapFragment);
fragmentTransaction.commit();
and its going to work like a charm.
Here is my manifest file:
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="8" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<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.docuart.maps.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>
</manifest>
And Here is my layout:
<?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:id="#+id/mapGoogle"
android:enabled="true"
android:clickable="true"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:apiKey="my api key" />
</LinearLayout>
Here is my code:
public class MainActivity extends MapActivity {
private static final int MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 1;//metre
private static final int MINIMUM_TIME_BETWEEN_UPDATES = 1000;//milisaniye
protected LocationManager locationManager;
MapView mView;
MapController mapController;
GeoPoint gPoint;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mView = (MapView) findViewById(R.id.mapGoogle);
mView.displayZoomControls(true);
mView.setBuiltInZoomControls(true);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MINIMUM_TIME_BETWEEN_UPDATES , MINIMUM_DISTANCE_CHANGE_FOR_UPDATES, new MyLocationListener());
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(location != null){
gPoint = new GeoPoint((int)(location.getLatitude()*1000000),(int)(location.getLongitude()*1000000));
mapController = mView.getController();
mapController.animateTo(gPoint);
mapController.setZoom(14);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public class MyLocationListener implements LocationListener{
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
gPoint = new GeoPoint((int)(location.getLatitude()*1000000),(int)(location.getLongitude()*1000000));
mapController = mView.getController();
mapController.animateTo(gPoint);
mapController.setZoom(14);
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}}
protected boolean isRouteDisplayed() {
return false;
}
}
Project running but i cant see my location. I cant find where is may fault. To see Screenshot: http://sdrv.ms/Wyf1Z1 Thank u for helping.
in your layout add your actual 2.0 auth api key in android:apiKey="my api key" />, which you must be reated from api key console .
Hello I am developing a map view I tried to following way
I created an "Intent" by clicking on a button]. Added permission and library
. I created an overlay item.
.My Emulator is targeted as GoogleApi 2.3.3 .My MapView key is obdained and asigned into mapview.xml
I am seeing the map with a google logo at bottom and map view controler: here is my code
MapView.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" >
<view android:id="#+id/mv"
class="com.google.android.maps.MapView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:clickable="true"
android:apiKey="046S_m5BQ43JIRtKiXQfldWwo2ddlU6dL6ca9SQ"
/>
</LinearLayout>
MapViewActivity.java
public class MapviewActivity extends MapActivity
{ private static double lat = 35.952967; // Temporary test values for lat/long
private static double lon = -83.929158 ;
private int latE6;
private int lonE6;
private MapController mapControl;
private GeoPoint gp;
private MapView mapView;
private LocationManager locationManager;
private MyOverlays itemizedoverlay;
private MyLocationOverlay myLocationOverlay;
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
//requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.mapview);
mapView = (MapView) findViewById(R.id.mv);
mapView.setBuiltInZoomControls(true);
mapView.setSatellite(true);
mapControl = mapView.getController();
mapControl.setZoom(12); // Zoon 1 is world view
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
0, new GeoUpdateHandler());
myLocationOverlay = new MyLocationOverlay(this, mapView);
mapView.getOverlays().add(myLocationOverlay);
myLocationOverlay.runOnFirstFix(new Runnable() {
public void run() {
mapView.getController().animateTo(
myLocationOverlay.getMyLocation());
}
});
Drawable drawable = this.getResources().getDrawable(R.drawable.point);
itemizedoverlay = new MyOverlays(this, drawable);
createMarker();
}
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);
createMarker();
mapControl.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) {
}
}
private void createMarker() {
GeoPoint p = mapView.getMapCenter();
OverlayItem overlayitem = new OverlayItem(p, "", "");
itemizedoverlay.addOverlay(overlayitem);
if (itemizedoverlay.size() > 0) {
mapView.getOverlays().add(itemizedoverlay);
}
}
#Override
protected void onResume() {
super.onResume();
myLocationOverlay.enableMyLocation();
myLocationOverlay.enableCompass();
}
#Override
protected void onPause() {
super.onResume();
myLocationOverlay.disableMyLocation();
myLocationOverlay.disableCompass();
}
// to set the satellite and traffic view
public boolean onKeyDown(int keyCode, KeyEvent e){
if(keyCode == KeyEvent.KEYCODE_S){
mapView.setSatellite(mapView.isSatellite());
return true;
} else if(keyCode == KeyEvent.KEYCODE_T){
mapView.setTraffic(mapView.isTraffic());
mapControl.animateTo(gp); // To ensure change displays immediately
}
return(super.onKeyDown(keyCode, e));
}
// Required method since class extends MapActivity
protected boolean isRouteDisplayed() {
return true; // display a route
}
here is my MyOverlays.java
public class MyOverlays extends ItemizedOverlay<OverlayItem> {
private static int maxNum = 5;
private OverlayItem overlays[] = new OverlayItem[maxNum];
private int index = 0;
private boolean full = false;
private Context context;
private OverlayItem previousoverlay;
public MyOverlays(Context context, Drawable defaultMarker) {
super(boundCenterBottom(defaultMarker));
this.context = context;
}
#Override
protected OverlayItem createItem(int i) {
return overlays[i];
}
#Override
public int size() {
if (full) {
return overlays.length;
} else {
return index;
}
}
public void addOverlay(OverlayItem overlay) {
if (previousoverlay != null) {
if (index < maxNum) {
overlays[index] = previousoverlay;
} else {
index = 0;
full = true;
overlays[index] = previousoverlay;
}
index++;
populate();
}
this.previousoverlay = overlay;
}
protected boolean onTap(int index) {
OverlayItem overlayItem = overlays[index];
Builder builder = new AlertDialog.Builder(context);
builder.setMessage("This will end the activity");
builder.setCancelable(true);
builder.setPositiveButton("I agree", new OkOnClickListener());
builder.setNegativeButton("No, no", new CancelOnClickListener());
AlertDialog dialog = builder.create();
dialog.show();
return true;
};
private final class CancelOnClickListener implements
DialogInterface.OnClickListener {
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(context, "You clicked yes", Toast.LENGTH_LONG)
.show();
}
}
private final class OkOnClickListener implements
DialogInterface.OnClickListener {
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(context, "You clicked no", Toast.LENGTH_LONG).show();
}
}
}
My Android.manifest
<uses-sdk android:minSdkVersion="10" />
<uses-permission android:name="android.permission.INTERNET" />
<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"/>
<application
android:icon="#drawable/drive_eat_icon"
android:label="#string/app_name" android:allowClearUserData="true" android:debuggable="true">
<activity
android:name=".MainScreen"
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=".DriveatmapActivity"></activity>
<activity android:name=".MapviewActivity"></activity>
<activity android:name=".FoodjointListActivity"></activity>
<activity android:name=".SubmitFormActivity"></activity>
<activity android:name=".MyOverlays"/>
<uses-library android:required="true" android:name="com.google.android.maps"></uses-library>
</application>
please suggest what to do . if you need any code please let me know.
I am seeing the google map with only grey tiles.
//instead of your view
//use this
<com.google.android.maps.MapView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/map_view"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:clickable="true"
android:enabled="true"
android:apiKey="046S_m5BQ43JIRtKiXQfldWwo2ddlU6dL6ca9SQ" />
Use it to get the Valid API key--
that is the exact path--
keytool -list -keystore "C:\Users\XYZ\.android\debug.keystore"
Total path for cmd prompt to get the MD5 fingureprint for the GoogleMap API Key----
if you are using eclipse then--
D:\eclipse\jre\bin>keytool -list -keystore "C:\Users\XYZ\.android\debug.keystore"
MD5 fingurePrint will look like this--
3E:F4:D6:E6:93:4D:BB:B8:62:3A:D6:0F:E0:FC:4C:65
When u get the fingurePrint number afterthat to get the API Key use this link---
http://code.google.com/android/add-ons/google-apis/maps-api-signup.html
Then u will get API key of your system and can get the Map easily instread of grids....
Use this key in your MapView.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
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/map"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:clickable="true"
android:enabled="true"
android:apiKey="046S_m5BQ43JIRtKiXQfldWwo2ddlU6dL6ca9SQ" />
</LinearLayout>