android - how to set current location in start of the app? -


i working on googlemap. code google developer site. struggling set current location when application starts.

i implement onmylocationbuttonclick() , when click, take me current location. implementing else. need show current location map view start. idea?

package com.jatinderbhola.mymapapp;  import com.google.android.gms.common.connectionresult; import com.google.android.gms.common.googleplayservicesutil; import com.google.android.gms.common.api.googleapiclient; import com.google.android.gms.location.locationservices; 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.googlemap.onmylocationbuttonclicklistener; import com.google.android.gms.maps.onmapreadycallback; import com.google.android.gms.maps.supportmapfragment; import com.google.android.gms.maps.model.cameraposition; import com.google.android.gms.maps.model.circleoptions; import com.google.android.gms.maps.model.latlng; import com.google.android.gms.maps.model.markeroptions;  import android.manifest; import android.app.dialog; import android.content.context; import android.content.pm.packagemanager; import android.location.criteria; import android.location.location; import android.location.locationlistener; import android.location.locationmanager; import android.os.bundle; import android.support.annotation.nonnull; import android.support.v4.app.activitycompat; import android.support.v4.content.contextcompat; import android.support.v7.app.appcompatactivity; import android.widget.toast;  /**  * demo shows how gms location can used check changes users location.   * "my location" button uses gms location set blue dot representing users location.  * permission {@link android.manifest.permission#access_fine_location} requested @ run  * time. if permission has not been granted, activity finished error message.  */ public class mapsactivity extends appcompatactivity         implements         onmylocationbuttonclicklistener,         onmapreadycallback,         activitycompat.onrequestpermissionsresultcallback,         locationlistener {      /**      * request code location permission request.      *      * @see #onrequestpermissionsresult(int, string[], int[])      */     private static final int location_permission_request_code = 1;      /**      * flag indicating whether requested permission has been denied after returning in      * {@link #onrequestpermissionsresult(int, string[], int[])}.      */     private boolean mpermissiondenied = false;      private googlemap mmap;     private locationmanager locationmanager;     private string provider;     private googlemap googlemap;      @override     protected void oncreate(bundle savedinstancestate) {         super.oncreate(savedinstancestate);         setcontentview(r.layout.activity_maps);          //         //setupmap();         supportmapfragment mapfragment =                 (supportmapfragment) getsupportfragmentmanager().findfragmentbyid(r.id.map);         mapfragment.getmapasync(this);     }     @override     public void onmapready(googlemap map) {         mmap = map;         mmap.setonmylocationbuttonclicklistener(this);         enablemylocation();     }      private void setupmap() {         mmap.addmarker(new markeroptions().position(new latlng(0, 0)).title("marker").snippet("snippet"));          // enable mylocation layer of google map         mmap.setmylocationenabled(true);          // locationmanager object system service location_service         locationmanager locationmanager = (locationmanager) getsystemservice(context.location_service);          // create criteria object retrieve provider         criteria criteria = new criteria();          // name of best provider         string provider = locationmanager.getbestprovider(criteria, true);          // current location         location mylocation = locationmanager.getlastknownlocation(provider);          // set map type         mmap.setmaptype(googlemap.map_type_normal);          // latitude of current location         double latitude = mylocation.getlatitude();          // longitude of current location         double longitude = mylocation.getlongitude();          // create latlng object current location         latlng latlng = new latlng(latitude, longitude);          // show current location in google map         mmap.movecamera(cameraupdatefactory.newlatlng(latlng));          // zoom in google map         mmap.animatecamera(cameraupdatefactory.zoomto(14));         mmap.addmarker(new markeroptions().position(new latlng(latitude, longitude)).title("you here!").snippet("consider located"));     }     /**      * enables location layer if fine location permission has been granted.      */     private void enablemylocation() {         if (contextcompat.checkselfpermission(this, manifest.permission.access_fine_location)                 != packagemanager.permission_granted) {             // permission access location missing.             permissionutils.requestpermission(this, location_permission_request_code,                     manifest.permission.access_fine_location, true);             setupmap();          } else if (mmap != null) {             // access location has been granted app.             mmap.setmylocationenabled(true);         }     }      @override     public boolean onmylocationbuttonclick() {         toast.maketext(this, "mylocation button clicked"+mmap.getmylocation().getlatitude(), toast.length_short).show();         // return false don't consume event , default behavior still occurs         // (the camera animates user's current position).         latlng sydney = new latlng(mmap.getmylocation().getlatitude(), mmap.getmylocation().getlongitude());         mmap.addmarker(new markeroptions().position(sydney).title("home"));         mmap.movecamera(cameraupdatefactory.newlatlng(sydney));         return false;     }       @override     public void onrequestpermissionsresult(int requestcode, @nonnull string[] permissions,                                            @nonnull int[] grantresults) {         if (requestcode != location_permission_request_code) {             return;         }          if (permissionutils.ispermissiongranted(permissions, grantresults,                 manifest.permission.access_fine_location)) {             // enable location layer if permission has been granted.             enablemylocation();         } else {             // display missing permission error dialog when fragments resume.             mpermissiondenied = true;         }     }      @override     protected void onresumefragments() {         super.onresumefragments();         if (mpermissiondenied) {             // permission not granted, display error dialog.             showmissingpermissionerror();             mpermissiondenied = false;         }     }      /**      * displays dialog error message explaining location permission missing.      */     private void showmissingpermissionerror() {         permissionutils.permissiondenieddialog                 .newinstance(true).show(getsupportfragmentmanager(), "dialog");     }       @override     public void onlocationchanged(location location) {      }      @override     public void onstatuschanged(string provider, int status, bundle extras) {      }      @override     public void onproviderenabled(string provider) {      }      @override     public void onproviderdisabled(string provider) {      } } 

i try use setupmap() leads following error. newbie in android.

02-05 15:35:11.303 19034-19034/com.jatinderbhola.mymapapp e/androidruntime: fatal exception: main process: com.jatinderbhola.mymapapp, pid: 19034 java.lang.runtimeexception: unable start activity componentinfo{com.jatinderbhola.mymapapp/com.jatinderbhola.mymapapp.mapsactivity}: java.lang.nullpointerexception: attempt invoke virtual method 'com.google.android.gms.maps.model.marker com.google.android.gms.maps.googlemap.addmarker(com.google.android.gms.maps.model.markeroptions)' on null object reference @ android.app.activitythread.performlaunchactivity(activitythread.java:2416) @ android.app.activitythread.handlelaunchactivity(activitythread.java:2476) @ android.app.activitythread.-wrap11(activitythread.java) @ android.app.activitythread$h.handlemessage(activitythread.java:1344) @ android.os.handler.dispatchmessage(handler.java:102) @ android.os.looper.loop(looper.java:148) @ android.app.activitythread.main(activitythread.java:5417) @ java.lang.reflect.method.invoke(native method) @ com.android.internal.os.zygoteinit$methodandargscaller.run(zygoteinit.java:726) @ com.android.internal.os.zygoteinit.main(zygoteinit.java:616) caused by: java.lang.nullpointerexception: attempt invoke virtual method 'com.google.android.gms.maps.model.marker com.google.android.gms.maps.googlemap.addmarker(com.google.android.gms.maps.model.markeroptions)' on null object reference @ com.jatinderbhola.mymapapp.mapsactivity.setupmap(mapsactivity.java:83) @ com.jatinderbhola.mymapapp.mapsactivity.oncreate(mapsactivity.java:70) @ android.app.activity.performcreate(activity.java:6237) @ android.app.instrumentation.callactivityoncreate(instrumentation.java:1107) @ android.app.activitythread.performlaunchactivity(activitythread.java:2369) @ android.app.activitythread.handlelaunchactivity(activitythread.java:2476)  @ android.app.activitythread.-wrap11(activitythread.java)  @ android.app.activitythread$h.handlemessage(activitythread.java:1344)  @ android.os.handler.dispatchmessage(handler.java:102)  @ android.os.looper.loop(looper.java:148)  @ android.app.activitythread.main(activitythread.java:5417)  @ java.lang.reflect.method.invoke(native method)  @ com.android.internal.os.zygoteinit$methodandargscaller.run(zygoteinit.java:726)  @ com.android.internal.os.zygoteinit.main(zygoteinit.java:616)  

thanks in advance.

you need animate camera position. can this.right after initiate map.

        location = locationmanager.getlastknownlocation(locationmanager.network_provider);      if(location != null){          cameraupdate position = cameraupdatefactory.newlatlng(new latlng(location.getlatitude(),location.getlongitude()));         mmap.animatecamera(position);     }      cameraupdate zoom= cameraupdatefactory.zoomto(15);     mmap.animatecamera(zoom); 

and won't work on emulator.if have actual phone use this.

    string provider = locationmanager.getbestprovider(criteria, true); 

or use manual providers.

      locationmanager.network_provider or gps_provider 

Comments

Popular posts from this blog

sublimetext3 - what keyboard shortcut is to comment/uncomment for this script tag in sublime -

java - No use of nillable="0" in SOAP Webservice -

ubuntu - Laravel 5.2 quickstart guide gives Not Found Error -