GoogleMap V2 不以用户当前位置开头

GoogleMap V2 doesn't start with user current location

我是 Android 的新手。我想开发一个简单的 GoogleMap 应用程序。但是我的应用程序不是从用户当前位置开始我的用户当前位置对象在应用程序启动时为空,当我按下菜单键并重新运行我的应用程序时,它显示但我想在应用程序启动时显示当前位置。

谢谢。

这是我的地图片段。

public class HaritaFragment extends Fragment implements LocationListener {

private static GoogleMap mGoogleMap;
public static HashMap<Marker, Markers> mMarkersHashMap = new HashMap<Marker, Markers>();
private ArrayList<Markers> mMyMarkersArray = new ArrayList<Markers>();
private Map<Marker, Markers> allMarkersMap = new HashMap<Marker, Markers>();

private Location location;
private Location defaultLocation;

private LatLng latLng;
private Double lat;
private Double lng;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    setHasOptionsMenu(true);
    return inflater.inflate(R.layout.fragment_harita, container, false);
}

public void onViewCreated(View view, Bundle savedInstanceState){
    googleAnalyticsSendScreen();

    // Getting Google Play availability status
    int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getActivity().getBaseContext());

    if (status != ConnectionResult.SUCCESS) { // Google Play Services are not available

        int requestCode = 10;
        Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, getActivity(), requestCode);
        dialog.show();

    } else { // Google Play Services are available


        mGoogleMap = ((SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map)).getMap();
        mGoogleMap.setMyLocationEnabled(true);

        LocationManager locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);

        Boolean isGPSProviderEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        Boolean isNetworkProviderEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);


        //TOOLBARS Disabled.
        mGoogleMap.getUiSettings().setMapToolbarEnabled(false);


        if (isNetworkProviderEnabled){
            location =  locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
            defaultLocation = mGoogleMap.getMyLocation();}

        if (isGPSProviderEnabled){
            location =  locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
            defaultLocation = mGoogleMap.getMyLocation();}
        else {

            if (mMyMarkersArray.isEmpty()){

                AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                builder.setTitle(R.string.location_error_title);
                builder.setMessage(R.string.location_error_message);
                builder.setPositiveButton(android.R.string.ok, null);

                AlertDialog dialog = builder.create();
                dialog.show();}
        }

        if (defaultLocation != null) {
            onLocationChanged(defaultLocation);
            latLng = new LatLng(lat, lng);
            mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 15));

        }
        //Location yoksa default value ve zoom value ile yaratıyor.
else if (defaultLocation != null){
    onLocationChanged(defaultLocation);

    latLng = new LatLng(lat, lng);
    mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 15));}

        else{

            Toast.makeText(getActivity(),"Still NULL",Toast.LENGTH_LONG).show();

            latLng = new LatLng(41.048846, 29.027924);
            mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 11));
        }
    }

}

@Override
public void onResume() {
    super.onResume();

    googleAnalyticsSendScreen();

    // Getting Google Play availability status
    int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getActivity().getBaseContext());

    if (status != ConnectionResult.SUCCESS) { // Google Play Services are not available

        int requestCode = 10;
        Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, getActivity(), requestCode);
        dialog.show();

    } else { // Google Play Services are available

        getAllDataFromParse();
        setUpMap();


    }
}

private void getAllDataFromParse(){

    if (mMyMarkersArray.isEmpty()){

        if (isInternetAvailable()){
            unPinMemberNO();
            getOnlineDataFromParse();
        }

        else{
            getOfflineDataFromParse();
        }
    }
}

private void unPinMemberNO(){

    ParseQuery<ParseObject> query = ParseQuery.getQuery("Veterinerler");
    query.setLimit(1000);
    query.whereEqualTo("isMember", "NO");
    ParseObject.unpinAllInBackground();
}

private void getOnlineDataFromParse(){

    ParseQuery<ParseObject> query = ParseQuery.getQuery("Veterinerler");
    query.setLimit(1000);
    query.whereEqualTo("isMember", "YES");
    query.findInBackground(new FindCallback<ParseObject>() {

        public void done(List<ParseObject> vetList, ParseException e) {
            if (e == null) {

                for(int i=0; i< vetList.size(); i++){

                    mMyMarkersArray.add(new Markers(

                            vetList.get(i).getString("adi"),
                            vetList.get(i).getString("adres"),
                            vetList.get(i).getString("telefon"),
                            vetList.get(i).getString("web"),
                            vetList.get(i).getString("face"),
                            vetList.get(i).getString("geceAcik"),
                            vetList.get(i).getDouble("latitude"),
                            vetList.get(i).getDouble("longitude")));
                }

                plotMarkers(mMyMarkersArray);
                ParseObject.pinAllInBackground(vetList);

            } else {

            }
        }
    });
}

private void getOfflineDataFromParse(){

    ParseQuery<ParseObject> query = ParseQuery.getQuery("Veterinerler");
    query.setLimit(1000);
    query.whereEqualTo("isMember", "YES");
    query.fromLocalDatastore();
    query.findInBackground(new FindCallback<ParseObject>() {

        public void done(List<ParseObject> vetList, ParseException e) {
            if (e == null) {

                for(int i=0; i< vetList.size(); i++){

                    mMyMarkersArray.add(new Markers(

                            vetList.get(i).getString("adi"),
                            vetList.get(i).getString("adres"),
                            vetList.get(i).getString("telefon"),
                            vetList.get(i).getString("web"),
                            vetList.get(i).getString("face"),
                            vetList.get(i).getString("geceAcik"),
                            vetList.get(i).getDouble("latitude"),
                            vetList.get(i).getDouble("longitude")));
                }

                plotMarkers(mMyMarkersArray);

            } else {

            }
        }
    });
}


private void googleAnalyticsSendScreen() {

    Tracker t = ((GlobalState) getActivity().getApplication()).getTracker(
            GlobalState.TrackerName.APP_TRACKER);
    t.setScreenName("Harita Ekranı");
    t.send(new HitBuilders.AppViewBuilder().build());
}

private void plotMarkers(ArrayList<Markers> markers)
{
    if(markers.size() > 0)
    {
        for (Markers myMarker : markers)
        {
            // Create user marker with custom icon and other options
            MarkerOptions markerOption = new MarkerOptions().position(new LatLng(myMarker.getmLatitude(), myMarker.getmLongtitude()));

            if (myMarker.getmGeceAcik().equalsIgnoreCase("YES")){

                markerOption.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
            }

            else if (myMarker.getmGeceAcik().equalsIgnoreCase("Cep")){

                markerOption.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
            }

            else if (myMarker.getmGeceAcik().equalsIgnoreCase("Barinak")){

                markerOption.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_VIOLET));
            }


            final Marker currentMarker = mGoogleMap.addMarker(markerOption);
            mMarkersHashMap.put(currentMarker, myMarker);
            allMarkersMap.put(currentMarker, myMarker);

            mGoogleMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
                @Override
                public View getInfoWindow(Marker marker) {

                    Markers selectedMarkerInfo = allMarkersMap.get(marker);

                    View v = View.inflate(getActivity().getBaseContext(),R.layout.info_window,null);

                    TextView tvAdi = (TextView) v.findViewById(R.id.tv_adi);
                    TextView tvAdres = (TextView) v.findViewById(R.id.tv_adres);
                    ImageView img = (ImageView) v.findViewById(R.id.img_icon);

                    tvAdi.setText(selectedMarkerInfo.getmAdi());
                    tvAdres.setText(selectedMarkerInfo.getmAdres());
                    tvAdi.setSelected(true);

                    if (selectedMarkerInfo.mGeceAcik.equalsIgnoreCase("Barinak")){

                        img.setImageResource(R.drawable.belediye);
                    }

                    else if (selectedMarkerInfo.mGeceAcik.equalsIgnoreCase("YES")){

                        img.setImageResource(R.drawable.gece_acik);
                    }

                    else if (selectedMarkerInfo.mGeceAcik.equalsIgnoreCase("Cep")){

                        img.setImageResource(R.drawable.acil);
                    }

                    else{

                        img.setImageResource(R.drawable.normal);
                    }
                    return v;
                }

                @Override
                public View getInfoContents(Marker marker) {

                    return null;
                }
            });
        }
    }
}

private void  setUpMap(){



            //OnClick Info Window Listener...
            mGoogleMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
                @Override
                public void onInfoWindowClick(Marker marker) {

                    Markers selectedMarkerInfo = allMarkersMap.get(marker);

                    //GOOGLE ANALYTICS EVENT SENDER
                    String secilenVeteriner = selectedMarkerInfo.getmAdi();
                    Tracker t = ((GlobalState) getActivity().getApplication()).getTracker(
                            GlobalState.TrackerName.APP_TRACKER);

                    t.send(new HitBuilders.EventBuilder()
                            .setCategory(secilenVeteriner)
                            .setAction("Harita ekranın'dan seçilme sayınız")
                            .setLabel("Harita")
                            .build());

                    Intent intent = new Intent(getActivity(), DetailActivity.class);

                    intent.putExtra("adi", selectedMarkerInfo.getmAdi());
                    intent.putExtra("adres", selectedMarkerInfo.getmAdres());
                    intent.putExtra("web", selectedMarkerInfo.getmWeb());
                    intent.putExtra("face", selectedMarkerInfo.getmFace());
                    intent.putExtra("tel", selectedMarkerInfo.getmTelefon());
                    intent.putExtra("lat", selectedMarkerInfo.getmLatitude().toString());
                    intent.putExtra("lng", selectedMarkerInfo.getmLongtitude().toString());
                    intent.putExtra("gece", selectedMarkerInfo.getmGeceAcik());

                    startActivity(intent);
                }
            });

}

private boolean isInternetAvailable() {
    ConnectivityManager connectivityManager
            = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}

@Override
public void onLocationChanged(Location location) {
        lat =  (location.getLatitude());
        lng =  (location.getLongitude());
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    if (id == R.id.action_mail) {

        Instabug.getInstance().setCommentFieldHint(getString(R.string.veterinerbildir_comment));
        Instabug.getInstance().enableEmailField(true,true);
        Instabug.getInstance().setCommentRequired(true);

        Instabug.getInstance().invokeFeedbackProcess(Instabug.INSTABUG_FEEDBACK_FEEDBACK);

        return true;
    }

    if (id == R.id.map_standart){

        mGoogleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);

    }

    if (id == R.id.map_hibrit){

        mGoogleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
    }

    if (id == R.id.map_uydu){

        mGoogleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
    }

    return super.onOptionsItemSelected(item);
}}

有我的MainActivity

public class MainActivity extends InstabugActionBarActivity implements ActionBar.TabListener {

SectionsPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
FragmentManager manager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    manager = getSupportFragmentManager();

    // Set up the action bar.
    final ActionBar actionBar = getSupportActionBar();
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

    getSupportActionBar().setDisplayShowHomeEnabled(true);
    getSupportActionBar().setLogo(R.drawable.nav_logo);
    getSupportActionBar().setDisplayUseLogoEnabled(true);
    getSupportActionBar().setTitle("");

    mSectionsPagerAdapter = new SectionsPagerAdapter(this, getSupportFragmentManager());

    mViewPager = (ViewPager) findViewById(R.id.pager);
    mViewPager.setAdapter(mSectionsPagerAdapter);
    mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
        @Override
        public void onPageSelected(int position) {
            actionBar.setSelectedNavigationItem(position);
        }
    });

    for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
        actionBar.addTab(
                actionBar.newTab()
                        //.setText(mSectionsPagerAdapter.getPageTitle(i))
                        .setIcon(mSectionsPagerAdapter.getIcon(i))
                        .setTabListener(this));
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.menu_main, menu);
    return super.onCreateOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    if (id == R.id.action_mail) {

        Instabug.getInstance().setCommentFieldHint(getString(R.string.veterinerbildir_comment));
        Instabug.getInstance().enableEmailField(true,true);
        Instabug.getInstance().setCommentRequired(true);

        Instabug.getInstance().invokeFeedbackProcess(Instabug.INSTABUG_FEEDBACK_FEEDBACK);

        return true;
    }

    else if (id == R.id.action_about){

        Intent intent = new Intent(this,InfoActivity.class);
        startActivity(intent);
    }

    return super.onOptionsItemSelected(item);
}

@Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
    mViewPager.setCurrentItem(tab.getPosition());


}

@Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}

@Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}

还有我的Fragment_ActivitiyXML

<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$HaritaFragment">


<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.SupportMapFragment"/>

和清单 XML

<!--
     The following two permissions are not required to use
     Google Maps Android API v2, but are recommended.
-->
<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_FINE_LOCATION" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

有LogCat输出

02-28 12:30:48.118  29049-29129/com.esmobileinc.vetmapp E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
        at com.esmobileinc.vetmapp.h.a(Unknown Source)
        at android.support.v4.app.Fragment.b(Unknown Source)
        at android.support.v4.app.v.a(Unknown Source)
        at android.support.v4.app.v.a(Unknown Source)
        at android.support.v4.app.e.run(Unknown Source)
        at android.support.v4.app.v.e(Unknown Source)
        at android.support.v4.app.v.b(Unknown Source)
        at android.support.v4.app.aa.b(Unknown Source)
        at android.support.v4.view.ViewPager.a(Unknown Source)
        at android.support.v4.view.ViewPager.c(Unknown Source)
        at android.support.v4.view.ViewPager.onMeasure(Unknown Source)
        at android.view.View.measure(View.java:13011)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4706)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:293)
        at android.view.View.measure(View.java:13011)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4706)
        at android.support.v7.internal.widget.ActionBarOverlayLayout.onMeasure(Unknown Source)
        at android.view.View.measure(View.java:13011)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4706)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:293)
        at android.view.View.measure(View.java:13011)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4706)
        at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1369)
        at android.widget.LinearLayout.measureVertical(LinearLayout.java:660)
        at android.widget.LinearLayout.onMeasure(LinearLayout.java:553)
        at android.view.View.measure(View.java:13011)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4706)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:293)
        at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2163)
        at android.view.View.measure(View.java:13011)
        at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1084)
        at android.view.ViewRootImpl.handleMessage(ViewRootImpl.java:2498)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:4944)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:511)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
        at dalvik.system.NativeStart.main(Native Method)

有什么问题吗?我只想使用用户位置启动我的应用程序。

谢谢!

我这样做了,就像你说的,但仍然不是从用户位置开始。

我认为您应该将 onResume() 中的所有代码移至 onViewCreated(),这是 Fragment 中执行所有此类设置的正确位置。

编辑:

您已将代码移至 onCreateView(),这与 onViewCreated() 不同。另外,地图初始化顺序不对

您的 onCreateView() 应如下所示:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
    Bundle savedInstanceState) {
    setHasOptionsMenu(true);
    return inflater.inflate(R.layout.fragment_harita, container, false);
}

并且您的地图初始化应该在 onViewCreated() 中完成,如下所示:

public void onViewCreated(View view, Bundle savedInstanceState){
    googleAnalyticsSendScreen();

    // Getting Google Play availability status
    int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getActivity().getBaseContext());

    if (status != ConnectionResult.SUCCESS) { // Google Play Services are not available

        int requestCode = 10;
        Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, getActivity(), requestCode);
        dialog.show();

    } else { // Google Play Services are available

        getAllDataFromParse();
        setUpMap();

        mGoogleMap = ((SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map)).getMap();
        mGoogleMap.setMyLocationEnabled(true);

        LocationManager locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);

        Boolean isGPSProviderEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        Boolean isNetworkProviderEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);


        //TOOLBARS Disabled.
        mGoogleMap.getUiSettings().setMapToolbarEnabled(false);


        if (isNetworkProviderEnabled){
            location =  locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
            defaultLocation = mGoogleMap.getMyLocation();}

            if (isGPSProviderEnabled){
                location =  locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        defaultLocation = mGoogleMap.getMyLocation();}
           else {

                if (mMyMarkersArray.isEmpty()){

                AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                builder.setTitle(R.string.location_error_title);
                builder.setMessage(R.string.location_error_message);
                builder.setPositiveButton(android.R.string.ok, null);

                AlertDialog dialog = builder.create();
                dialog.show();}
          }

          if (defaultLocation != null) {
              onLocationChanged(defaultLocation);
              latLng = new LatLng(lat, lng);
              mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 15));

    }
   //Location yoksa default value ve zoom value ile yaratıyor.
   /* else if (defaultLocation != null){
        onLocationChanged(defaultLocation);

        latLng = new LatLng(lat, lng);
        mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 15));}*/

            else{
                latLng = new LatLng(41.048846, 29.027924);
                mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 11));
        }
    }

}