Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/215.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 如何在片段中获取当前位置的谷歌地图?_Android_Google Maps_Android Layout - Fatal编程技术网

Android 如何在片段中获取当前位置的谷歌地图?

Android 如何在片段中获取当前位置的谷歌地图?,android,google-maps,android-layout,Android,Google Maps,Android Layout,这是获取我的当前位置并显示该位置的详细信息,但我想做的是能够有一个谷歌地图显示以及我的当前位置,我需要在一个片段中这样做 源代码如下所示 package location.com.prjlocationdemo; import android.Manifest; import android.content.Context; import android.content.pm.PackageManager; import android.location.Address; import and

这是获取我的当前位置并显示该位置的详细信息,但我想做的是能够有一个谷歌地图显示以及我的当前位置,我需要在一个片段中这样做

源代码如下所示

package location.com.prjlocationdemo;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;
import java.util.List;

public class GetMyAddress extends AppCompatActivity
{

    TextView AddressText;
    Geocoder objCoder;
    String provider;
    Criteria objCriteria;
    LocationManager objLocationManager;
    Location objLocation;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_get_my_address);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        AddressText = (TextView) findViewById(R.id.tvMyAddress);
        objCriteria = new Criteria();
        objLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        objCriteria.setAccuracy(Criteria.NO_REQUIREMENT);
        objCriteria.setPowerRequirement(Criteria.NO_REQUIREMENT);
      //  provider = objLocationManager.getBestProvider(objCriteria,true);
        provider = objLocationManager.NETWORK_PROVIDER;
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
        {
            // TODO: Consider calling
            //    ActivityCompat#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 ActivityCompat#requestPermissions for more details.
            return;
        }
        objLocationManager.requestLocationUpdates(provider, 1000, 0, new LocationListener()
        {
            @Override
            public void onLocationChanged(Location location)
            {

            }

            @Override
            public void onStatusChanged(String provider, int status, Bundle extras)
            {

            }

            @Override
            public void onProviderEnabled(String provider)
            {
                Toast.makeText(GetMyAddress.this, "Location On", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onProviderDisabled(String provider)
            {
                Toast.makeText(GetMyAddress.this, "Location Off", Toast.LENGTH_SHORT).show();
            }
        });


    }
    //*********************************************************************************************************
    public void btnClick(View v)
    {
        RetrieveLocation objAddress = new RetrieveLocation();
        objAddress.execute(objLocation);
    }
    //*********************************************************************************************************
    public class RetrieveLocation extends AsyncTask<Location, Void, String>
    {

        @Override
        protected void onPreExecute()
        {
            Toast.makeText(getApplication(), "Finding Your Location....", Toast.LENGTH_SHORT).show();
        }
        //***************************************************************************
        @Override
        protected String doInBackground(Location... params)
        {
            String myAddress = null;
            if (Geocoder.isPresent())
            {
                objCoder = new Geocoder(getApplicationContext());
                if (ActivityCompat.checkSelfPermission(GetMyAddress.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(GetMyAddress.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
                {
                    // TODO: Consider calling
                    //    ActivityCompat#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 ActivityCompat#requestPermissions for more details.
                    return "";
                }



                params[0] = objLocationManager.getLastKnownLocation(provider);
                if (params[0] != null)
                {
                    List<Address> objAddressList = null;
                    try
                    {
                        objAddressList = objCoder.getFromLocation(params[0].getLatitude(), params[0].getLongitude(), 1);
                        if (objAddressList != null)
                        {
                            for (Address addressLoc : objAddressList)
                            {
                                String city = addressLoc.getLocality();
                                String country = addressLoc.getCountryName();
                                String place = addressLoc.getFeatureName();
                                String road = addressLoc.getSubThoroughfare();
                                String postal = addressLoc.getPostalCode();
                                myAddress = "Address\n City : " + city +
                                        "\nCountry : " + country +
                                        "\nName Of Place : " + place +
                                        "\nRoad : " + road +
                                        "\nPostal Code : " + postal + "\n";

                                int addressIndex = addressLoc.getMaxAddressLineIndex();
                                for (int count = 0; count <= addressIndex; count++)
                                {
                                    String line = addressLoc.getAddressLine(count);
                                    myAddress += line + "\n";
                                }
                            }
                        }
                        else
                        {
                            return "No Location Found";
                        }
                    }
                    catch (IOException e)
                    {
                        e.printStackTrace();
                    }
                }
                else
                {
                    return "Nothing Found";
                }
            }
            return myAddress;
        }
        //****************************************************************************************
        @Override
        protected void onPostExecute(String s)
        {
           AddressText.setText(s);
            Log.d("Prov",provider);
        }
    }
}


你可以使用布局的这一部分

基本上,你有一个在活动上运行良好的代码,你想把它放在一个片段上吗?是的,看XML下面,这就是我需要添加的内容。是的,我知道,并且做了类似的事情,但这不是我想要的。。。
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="location.com.prjlocationdemo.GetMyAddress"
    tools:showIn="@layout/activity_get_my_address">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="My Address"
        android:id="@+id/tvMyAddress"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="86dp" />

    <Button
        style="?android:attr/buttonStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Get My Address"
        android:id="@+id/btnAddress"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="125dp"
        android:onClick="btnClick"/>
</RelativeLayout>
public class FragmentTwo extends Fragment
{
    MapView mapView;
    GoogleMap map;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_fragment_two, container, false);


        // Gets the MapView from the XML layout and creates it
        mapView = (MapView) v.findViewById(R.id.mapview);
        mapView.onCreate(savedInstanceState);

        // Gets to GoogleMap from the MapView and does initialization stuff
        map = mapView.getMap();
        map.getUiSettings().setMyLocationButtonEnabled(false);
        map.setMyLocationEnabled(true);

        // Needs to call MapsInitializer before doing any CameraUpdateFactory calls
        try {
            MapsInitializer.initialize(this.getActivity());
        } catch (GooglePlayServicesNotAvailableException e) {
            e.printStackTrace();
        }

        // Updates the location and zoom of the MapView
        CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new LatLng(43.1, -87.9), 10);
        map.animateCamera(cameraUpdate);

        return v;
    }

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

    @Override
    public void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        mapView.onLowMemory();
    }

}
 <LinearLayout
    android:orientation="vertical"
    android:minWidth="25px"
    android:minHeight="25px"
    android:layout_width="match_parent"
    android:layout_height="280dp"
    android:id="@+id/mapLay"
    android:background="@color/blue25">
    <fragment xmlns:map="http://schemas.android.com/apk/res-auto"
        android:id="@+id/map"
        android:name="com.google.android.gms.maps.SupportMapFragment"
        tools:context="com.example.k.guides4art20.MapsActivity"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>