In my android app, with a Navigation Drawer, I have a problem with a fragment in which I use a mapview: when i launch the fragment for the first time, it shows only the first of one list of markers I want to draw. I have to reload the fragment to see all the markers draw on the map (or for example click on another voice on the menu and after again on the map fragment). I have the feeling that the fragment launch the map before all the markers are draw. Can it be the problem? How could I fix it? This is my code:
public class MapFragment extends Fragment implements OnMapReadyCallback, GoogleMap.OnInfoWindowClickListener {
private GoogleMap mGoogleMap;
private MapView mMapView;
private View mView;
public MapFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
mView = inflater.inflate(R.layout.map_fragment, container, false);
return mView;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mMapView = mView.findViewById(R.id.map);
if (mMapView != null) {
mMapView.onCreate(null);
mMapView.onResume();
mMapView.getMapAsync(this);
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
mGoogleMap = googleMap;
drawMarkerOnTheMap(mGoogleMap);
mGoogleMap.getUiSettings().setZoomControlsEnabled(true);
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
LatLng city = new LatLng(40.679425, 14.755968);
CameraPosition camera = CameraPosition.builder().target(city).zoom(15).build();
mGoogleMap.moveCamera(CameraUpdateFactory.newCameraPosition(camera));
}
private void drawMarkerOnTheMap(GoogleMap googleMap) {
try {
InputStream is = getContext().getAssets().open("turisticpoint.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(is);
Element element=doc.getDocumentElement();
element.normalize();
NodeList nList = doc.getElementsByTagName("turisticpoint");
for (int i=0; i<nList.getLength(); i++) {
Node node = nList.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element element2 = (Element) node;
String title = getValue("title", element2);
String tit = getContext().getResources().getString(getContext().getResources().getIdentifier(title, "string", getActivity().getPackageName()));
Double latitude = Double.valueOf(getValue("latitude", element2));
Double longitude= Double.valueOf(getValue("longitude", element2));
LatLng position = new LatLng(latitude, longitude);
MarkerOptions marker = new MarkerOptions().
position(position).
title(tit)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE));
googleMap.addMarker(marker);
}
}
} catch (Exception e) {e.printStackTrace();}
}
private static String getValue(String tag, Element element) {
NodeList nodeList = element.getElementsByTagName(tag).item(0).getChildNodes();
Node node = nodeList.item(0);
return node.getNodeValue();
}
}
In my logcat I just found this error:
E/libprocessgroup: failed to make and chown /acct/uid_10063: Read-only file system
this is my manifest file:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="package">
<supports-screens
android:anyDensity="true"
android:largeScreens="true"
android:normalScreens="true"
android:smallScreens="true"
android:xlargeScreens="true" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<application
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=".HomeActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="#string/google_maps_key" />
<activity
android:name=".MainActivity"
android:label="MyApp"
android:theme="#style/AppTheme.NoActionBar"></activity>
</application>
</manifest>
and my build.gradle:
apply plugin: 'com.android.application'
android {
compileSdkVersion 28
defaultConfig {
applicationId "myappId"
minSdkVersion 15
targetSdkVersion 28
multiDexEnabled true
versionCode 16
versionName "1.5"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
missingDimensionStrategy 'minApi', 'minApi18', 'minApi23'
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support:support-v4:28.0.0'
implementation 'com.android.support:design:28.0.0'
implementation 'com.google.android.gms:play-services-maps:16.1.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}
and this is an xml file similar to mine:
<records>
<turisticpoint>
<titolo>Gardens</titolo>
<latitudine>40.678480</latitudine>
<longitudine>14.753152</longitudine>
</turisticpoint>
<turisticpoint>
<titolo>Castle</titolo>
<latitudine>40.6794731</latitudine>
<longitudine>14.7544442</longitudine>
</turisticpoint>
<turisticpoint>
<titolo>Beach</titolo>
<latitudine>40.6965378</latitudine>
<longitudine>14.7777038</longitudine>
</turisticpoint>
</records>
in total I have 13 turistic point.
Related
I am looking to display a Google Maps Display on a fragment layout within android studio. I have already downloaded Google play services in the SDK and have made the appropriate changes to my gradle files (I Think). I have made some changes to the android manifest file as well to grant user permissions etc. At run time a google maps display renders but the lng and lat are set to 0 so when the map displays, it shows me an area around Africa. I have made methods in the java file such as onMapReady, which is supposed to display the map at a different location and have it more zoomed in. The onMapReady function calls another method called goToLocationZoom, which holds the required functionality to allow the map to move to this location but for some reason everytime I run it, it always stays to the area around Africa, even though I have changed the lng and lat values. I am following a tutorial to achieve this, and in there Activty_home.XML file, they have their layout to linear, whilst mine is set to constraint but I don't think this would cause the issue. Does anyone know how to display the map to the lng and lat values that I have specified in the java file?
Below is my Java file code:
com.example.cmpkbest.lifestylefitnessapp;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
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.OnMapReadyCallback;
import com.google.android.gms.maps.model.LatLng;
public class ViewLifestyles extends AppCompatActivity implements
GoogleMap mGoogleMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_lifestyles);
initMap();
}
private void initMap () {
MapFragment mapFragment = (MapFragment) getFragmentManager ().findFragmentById(R.id.mapFragment);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mGoogleMap = googleMap;
goToLocationZoom (53.408743, -2.984154, 15);
}
private void goToLocation (double lat, double lng) {
LatLng ll = new LatLng(lat, lng);
CameraUpdate update = CameraUpdateFactory.newLatLng(ll);
mGoogleMap.moveCamera(update);
}
private void goToLocationZoom (double lat, double lng, float zoom) {
LatLng ll = new LatLng(lat, lng);
CameraUpdate update = CameraUpdateFactory.newLatLngZoom(ll, zoom);
mGoogleMap.moveCamera(update);
}
}
Below is my Manifest code:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.cmpkbest.lifestylefitnessapp">
<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" />
<permission android:name="com.example.cmpkbest.lifestylefitnessapp.permission.MAPS_RECIEVE"
android:protectionLevel="signature" />
<uses-permission android:name="com.example.cmpkbest.lifestylefitnessapp.permission.MAPS_RECIEVE" />
<uses-permission android:name="com.google.android.providers.gsf.permissions.READ_GSERVICES" />
<uses-feature android:glEsVersion="0x00020000"
android:required="true" />
<application
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=".RegistrationPage">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".Login" />
<activity android:name=".Home" />
<activity android:name=".ViewLifestyles" />
<activity android:name=".Workouts" />
<activity android:name=".Notemaker"></activity>
<meta-data android:name="com.google.android.maps.v2.API_KEY"
android:value="AIzaSyAkAQlA2B8_E5pPNH_jdAWSJpf915uozi8 " />
<meta-data android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
</application>
</manifest>
Below is my Gradle Files:
apply plugin: 'com.android.application'
repositories {
maven {
url 'https://maven.google.com'
}
}
android {
compileSdkVersion 25
buildToolsVersion "25.0.3"
defaultConfig {
applicationId "com.example.cmpkbest.lifestylefitnessapp"
minSdkVersion 23
targetSdkVersion 25
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:25.3.1'
compile 'com.android.support.constraint:constraint-layout:+'
testCompile 'junit:junit:4.12'
compile 'com.google.android.gms:play-services-maps:11.0.4'
}
Finally, my Layout.XML file
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/bg5"
tools:context="com.example.cmpkbest.lifestylefitnessapp.ViewLifestyles"
tools:layout_editor_absoluteY="81dp"
tools:layout_editor_absoluteX="0dp">
<fragment
android:id="#+id/mapFragment"
android:name="com.google.android.gms.maps.MapFragment"
android:layout_width="346dp"
android:layout_height="212dp"
app:layout_constraintBottom_toBottomOf="parent"
android:layout_marginBottom="8dp"
app:layout_constraintTop_toTopOf="parent"
android:layout_marginTop="8dp"
android:layout_marginRight="8dp"
app:layout_constraintRight_toRightOf="parent"
android:layout_marginLeft="8dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintVertical_bias="0.084" />
</android.support.constraint.ConstraintLayout>
I also had a project doing same output. I handle it this way.
So first you have to initialize the map
if (mMap == null) {
mMap = ((MapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap();
// check if map is created successfully or not
if (mMap == null) {
Toast.makeText(getApplicationContext(),
"Sorry! unable to create maps", Toast.LENGTH_SHORT)
.show();
}
}
Then i call setUpMap right after initializing it, not relying on onMapReady
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(
lastLocation.getLatitude(), lastLocation.getLongitude()), 15));
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
mMap.setIndoorEnabled(true);
mMap.setMyLocationEnabled(true);
Hope this helps
I have created activity: MapsActivity, which shows my location on map.
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
private LocationManager locationManager;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
Location location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, false));
double lat = location.getLatitude();
double lng = location.getLongitude();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mMap.setMyLocationEnabled(true);
// Add a marker in Sydney and move the camera
LatLng place = new LatLng(lat,lng);
mMap.addMarker(new MarkerOptions().position(place).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(place));
}
}
I created MainActivity, with a button, which I want to click to move to MapsActivity, here it's code:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void showMyLocation(View view){
Intent intentControls = new Intent(this, MapsActivity.class);
startActivity(intentControls);
}
}
Gradle
android {
compileSdkVersion 27
buildToolsVersion "27.0.1"
defaultConfig {
applicationId "com.example.lukasz.aaaaa"
minSdkVersion 21
targetSdkVersion 27
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:26.0.0-alpha1'
compile 'com.google.android.gms:play-services-maps:10.2.6'
compile 'com.android.support.constraint:constraint-layout:1.0.0-alpha8'
testCompile 'junit:junit:4.12'
}
AndroidManifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.lukasz.aaaaa">
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<application
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">
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="#string/google_maps_key" />
<activity
android:name=".MapsActivity"
android:label="#string/title_activity_maps">
</activity>
<activity android:name=".MainActivity"
android:label="Mapy">>
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
The problem is, that after I click the button in my MainActivity, the application crashes with
FATAL EXCEPTION: main
Process: com.example.lukasz.aaaaa, PID: 2433
java.lang.IllegalArgumentException: invalid provider: null
at android.location.LocationManager.checkProvider(LocationManager.java:2099)
at android.location.LocationManager.getLastKnownLocation(LocationManager.java:1200)
at com.example.lukasz.aaaaa.MapsActivity.onMapReady(MapsActivity.java:56)
at com.google.android.gms.maps.SupportMapFragment$zza$1.zza(Unknown Source:7)
at com.google.android.gms.maps.internal.zzt$zza.onTransact(Unknown Source:30)
at android.os.Binder.transact(Binder.java:627)
at gl.b(:com.google.android.gms.DynamiteModulesB#11577470:20)
at com.google.android.gms.maps.internal.bf.a(:com.google.android.gms.DynamiteModulesB#11577470:5)
at com.google.maps.api.android.lib6.impl.bc.run(:com.google.android.gms.DynamiteModulesB#11577470:5)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)r
My question is how do I run Google Map Activity from another activity, using Intent?
keep below permission above application Tag
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<application
......
.....
<activity>
.....
</activity>
</application>
(or)
You are getting this error most probably, due to un-availability of
GPS Providers. Please ask the person to check settings if Gps
Provider or Network Provider has been enabled into Location
settings.
I am doing what is written in this link but it isn't working(image1)(line 46, 47 and 53) https://io2015codelabs.appspot.com/codelabs/fire-place#7
for image ->
MapsActiviy.java
import android.location.Location;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.content.ContextCompat;
import android.view.ViewTreeObserver;
import android.widget.Button;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMyLocationChangeListener;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
private LatLngBounds.Builder mBounds = new LatLngBounds.Builder();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Set up Google Maps
SupportMapFragment mapFragment = (SupportMapFragment)
getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
/**
* Map setup. This is called when the GoogleMap is available to manipulate.
*/
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Pad the map controls to make room for the button - note that the button may not have
// been laid out yet.
final Button button = (Button) findViewById(R.id.checkout_button);
button.getViewTreeObserver().addOnGlobalLayoutListener(
new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
mMap.setPadding(0, button.getHeight(), 0, 0);
}
}
);
mMap.setMyLocationEnabled(true);
mMap.setOnMyLocationChangeListener(new OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location location) {
LatLng ll = new LatLng(location.getLatitude(), location.getLongitude());
addPointToViewPort(ll);
// we only want to grab the location once, to allow the user to pan and zoom freely.
mMap.setOnMyLocationChangeListener(null);
}
});
}
private void addPointToViewPort(LatLng newPoint) {
mBounds.include(newPoint);
mMap.animateCamera(CameraUpdateFactory.newLatLngBounds(mBounds.build(),
findViewById(R.id.checkout_button).getHeight()));
}
}
activity_maps.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="match_parent"
android:layout_width="match_parent">
<Button android:id="#+id/checkout_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/check_out"
android:onClick="checkOut"/>
<fragment 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:id="#+id/map"
tools:context=".MapsActivity"
android:name="com.google.android.gms.maps.SupportMapFragment"/>
</FrameLayout>
build.gradle(Module: App)
apply plugin: 'com.android.application'
android {
compileSdkVersion 23
buildToolsVersion '23.0.3'
defaultConfig {
applicationId "com.sahikaaylin.checkout"
minSdkVersion 19
targetSdkVersion 23
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
productFlavors {
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.google.android.gms:play-services:9.0.1'
compile 'com.firebase:firebase-client-android:2.3.1'
compile 'com.android.support:appcompat-v7:23.4.0'
}
for manifest.xml
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme" >
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="#string/google_maps_key" />
<activity
android:name=".MapsActivity"
android:label="#string/title_activity_maps" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
As seen on the Android docs : https://developers.google.com/android/reference/com/google/android/gms/maps/GoogleMap.OnMyLocationChangeListener
GoogleMap.OnMyLocationChangeListener is now deprecated. The tutorial you are using is simply already too old.
From the link above, you will be able to be redirected to newer tutorials and how-to guides (which will also solve the setMyLocationEnabled error).
EDIT : What I recommended is now deprecated, such is life in software development. If you're looking for the newest way of doing it, check out the Android documentations.
After tons of tries I couldn't found how to solve this.
Android won't resolve the symbol 'mapView' on:
mMapView = (MapView) v.findViewById(R.id.mapView);
What i'm trying to do is to get google maps to work on the emulator.
I know this code is working on another PC, so my guess here that there's something else.. (a system issue or google maps api problem)
here's the code.
Can anyone help? Thank you..
package com.example.matant.gpsportclient.Controllers;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.matant.gpsportclient.AsyncResponse;
import com.example.matant.gpsportclient.R;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.MapsInitializer;
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;
/**
* Created by matant on 8/24/2015.
*/
public class GoogleMapFragmentController extends Fragment implements AsyncResponse {
MapView mMapView;
private GoogleMap googleMap;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// inflat and return the layout
View v = inflater.inflate(R.layout.fragment_google_map_fragment_controller, container,
false);
mMapView = (MapView) v.findViewById(R.id.mapView);
mMapView.onCreate(savedInstanceState);
mMapView.onResume();// display map immediately
try {
MapsInitializer.initialize(getActivity().getApplicationContext());
} catch (Exception e) {
e.printStackTrace();
}
googleMap = mMapView.getMap();
// latitude and longitude
double latitude = 17.385044;
double longitude = 78.486671;
// create marker
MarkerOptions marker = new MarkerOptions().position(
new LatLng(latitude, longitude)).title("Hello Maps");
// Changing marker icon
marker.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ROSE));
// adding marker
googleMap.addMarker(marker);
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(17.385044, 78.486671)).zoom(12).build();
googleMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
googleMap.getUiSettings().setZoomControlsEnabled(true);
// Perform any camera updates here
return v;
}
#Override
public void onResume() {
super.onResume();
mMapView.onResume();
}
#Override
public void onPause() {
super.onPause();
mMapView.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
mMapView.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mMapView.onLowMemory();
}
#Override
public void handleResponse(String resStr) {
}
#Override
public void sendDataToDBController() {
}
#Override
public void preProcess() {
}
}
Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.matant.gpsportclient"
android:versionCode="1"
android:versionName="1.0" >
<uses-feature
android:glEsVersion="0x00020000"
android:required="true" />
<uses-sdk
android:minSdkVersion="17"
android:targetSdkVersion="17" />
<permission
android:name="com.example.matant.gpsportclient.permission.MAPS_RECEIVE"
android:protectionLevel="signature" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.MANAGE_DOCUMENTS" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="com.example.matant.gpsportclient.permission.MAPS_RECEIVE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".SplashScreen"
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=".Controllers.ForgotPassword"
android:label="#string/app_name" >
</activity>
<activity
android:name=".Controllers.Login"
android:label="#string/title_activity_login" >
</activity>
<activity
android:name=".Controllers.SignUp"
android:label="#string/title_activity_sign_up" >
</activity>
<activity
android:name=".MainScreen"
android:label="#string/title_activity_main_screen" >
</activity>
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="#string/google_maps_key" />
</application>
</manifest>
build.gradle:
apply plugin: 'com.android.application'
android {
compileSdkVersion 21
buildToolsVersion "23.0.0 "
defaultConfig {
applicationId "com.example.matant.gpsportclient"
minSdkVersion 23
targetSdkVersion 22
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
productFlavors {
}
}
dependencies {
compile files('C:/Users/Adi/AndroidStudioProjects/GPSportClient/libs/additionnal.jar')
compile files('C:/Users/Adi/AndroidStudioProjects/GPSportClient/libs/mail.jar')
compile files('C:/Users/Adi/AndroidStudioProjects/GPSportClient/libs/activation.jar')
compile fileTree(include: ['*.jar'], dir: 'libs')
compile 'com.android.support:appcompat-v7:22.2.1'
compile 'com.google.android.gms:play-services-maps:7.8.0'
}
Layout:
<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>
Replace
mMapView = (MapView) v.findViewById(R.id.mapView);
with
mMapView = (MapView) v.findViewById(R.id.map);
as the id of your fragment is map. See the xml
<fragment
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.MapFragment" />
I am trying to load google map in emulator for a given latitude and longitude.
Map is loading in the emulator but no marker is coming and same view is shown always.
i have followed the tutorial. Below is my code.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
double latitude = getIntent().getDoubleExtra("lat", 0);
double longitude = getIntent().getDoubleExtra("lng", 0);
Log.d("Zumbare","lat value : "+latitude);
Log.d("Zumbare","lng value : "+longitude);
LatLng position = new LatLng(latitude, longitude);
MarkerOptions options = new MarkerOptions();
options.position(position);
options.title("Position");
options.snippet("Latitude:"+latitude+",Longitude:"+longitude);
options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
SupportMapFragment fm = (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map);
GoogleMap googleMap = fm.getMap();
googleMap.setMyLocationEnabled(true);
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
googleMap.getUiSettings().setZoomControlsEnabled(true);
googleMap.getUiSettings().setCompassEnabled(true);
googleMap.addMarker(options);
CameraUpdate updatePosition = CameraUpdateFactory.newLatLng(position);
CameraUpdate updateZoom = CameraUpdateFactory.zoomBy(4);
googleMap.moveCamera(updatePosition);
googleMap.animateCamera(updateZoom);
}
Below is my manifest file.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.app.maptest.gmap" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<permission
android:name="com.app.maptest.gmap.MAPS_RECEIVE"
android:protectionLevel="signature"/>
<uses-permission android:name="com.app.maptest.gmap.MAPS_RECEIVE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-feature
android:glEsVersion="0x00020000"
android:required="true"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
</activity>
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="AIzaSyCInpkx8MO-lD4AMR4aUYns3tVvUMjIH1k" />
<activity
android:name=".MainActivity2"
android:label="#string/title_activity_main_activity2" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Can someone help me where the problem is..
Edit :
Yes, I am fetching lat lng of a city and logs are coming as..
1885-1885/com.app.maptest.gmap D/Zumbareļ¹ lat value : 16.506174
03-29 16:20:54.602 1885-1885/com.app.maptest.gmap D/Zumbareļ¹ lng value : 80.648015
Edit2:
I am using android studio and added the google play service in gradle file as below.
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:22.0.0'
compile 'com.google.android.gms:play-services:3.1.36'
}
I think the tutorial that you followed is outdated. play-services now is 6.5.87.
Please try to follow this step by step, you will finally get a map on your phone.
MainAcitivity, sample code:
public class MainActivity extends Activity {
private static LatLng goodLatLng = new LatLng(37, -120);
private GoogleMap googleMap;
private EditText et_address, et_finalAddress;
LatLng addressPos, finalAddressPos;
Marker addressMarker;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_address = (EditText) findViewById(R.id.addressEditText);
et_finalAddress = (EditText) findViewById(R.id.finalAddressEditText);
// Initial Map
try {
if (googleMap == null) {
googleMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
}
} catch (Exception e) {
e.printStackTrace();
}
googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
// Put a dot on my current location
googleMap.setMyLocationEnabled(true);
googleMap.setIndoorEnabled(true);
googleMap.setTrafficEnabled(true);
// 3D building
googleMap.setBuildingsEnabled(true);
// Get zoom button
googleMap.getUiSettings().setZoomControlsEnabled(true);
Marker marker = googleMap.addMarker(new MarkerOptions()
.position(goodLatLng)
.title("Hello"));
}
For more details, please refer to my github here.