2016-09-14 124 views
-1

这是得到我的当前位置,并显示该位置的详细信息,但我想要做的是能够有一个谷歌地图显示以及我目前的位置,我需要做一个片段。如何获得当前位置的谷歌地图片段?

源是下面的代码

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> 

我试图把它添加到它 但得到map = mapView.getMap();map.setMyLocationEnabled(true);catch (GooglePlayServicesNotAvailableException e) {e.printStackTrace();}是给我的错误。

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(); 
    } 

} 
+1

基本上这部分你有在某个活动中正常工作守则,你想要把它放在一个片段? –

+0

是的,请参阅XML,这是我需要添加它。 –

回答

0
<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> 

您可以使用布局

+0

是的,我知道,并做了类似的事情,但最新不是我想要的... –