映射片段中的当前位置

时间:2017-01-17 10:44:13

标签: android google-maps fragment currentlocation

我们在活动中获取代码。但是无法在fragment中实现。这是activity中的代码。请帮助我们找到片段中的当前位置。 我们能够将标记放入片段中,但是我们无法获得片段中的当前位置。请在我们处理地图的应用程序时帮助我们。

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback,
    GoogleApiClient.ConnectionCallbacks,
    GoogleApiClient.OnConnectionFailedListener,
    LocationListener {
private GoogleMap mMap;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker;
LocationRequest mLocationRequest;
ArrayList<LatLng> markerPoints=new ArrayList<LatLng>();
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_map);
    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        checkLocationPermission();
    }
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map1);
    mapFragment.getMapAsync(this);
}
@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED) {
            buildGoogleApiClient();
            mMap.setMyLocationEnabled(true);
        }
    }
    else {
        buildGoogleApiClient();
        mMap.setMyLocationEnabled(true);
    }
    mMap.addMarker(new MarkerOptions()
            .title("Delivered")
            .position(new LatLng(10.01, 76.34)));
    mMap.addMarker(new MarkerOptions()
            .title("Delivered")
            .position(new LatLng(9.99, 76.31)));
    mMap.addMarker(new MarkerOptions()
            .title("Delivered")
            .position(new LatLng(9.99, 76.30)));
    mMap.addMarker(new MarkerOptions()
            .title("Delivered")
            .position(new LatLng(10.52, 76.21)));
    markerPoints.add(new LatLng(10.01, 76.34));
    markerPoints.add(new LatLng(9.99, 76.31));
    markerPoints.add(new LatLng(9.99, 76.30));
    markerPoints.add(new LatLng(10.52, 76.21));
    mMap.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener() {
        @Override
        public void onMapLongClick(LatLng point) {
            mMap.clear();
            markerPoints.clear();
        }
    });
}
private String getDirectionsUrl(LatLng origin,LatLng dest){
    String str_origin = "origin="+origin.latitude+","+origin.longitude;
    String str_dest = "destination="+dest.latitude+","+dest.longitude;
    String sensor = "sensor=false";
    String waypoints = "";
    for(int i=2;i<markerPoints.size();i++){
        LatLng point  = (LatLng) markerPoints.get(i);
        if(i==2)
            waypoints = "waypoints=";
        waypoints += point.latitude + "," + point.longitude + "|";
    }
    String parameters = str_origin+"&"+str_dest+"&"+sensor+"&"+waypoints;
    String output = "json";
    String url = "https://maps.googleapis.com/maps/api/directions/"+output+"?"+parameters;
    return url;
}
private String downloadUrl(String strUrl) throws IOException {
    String data = "";
    InputStream iStream = null;
    HttpURLConnection urlConnection = null;
    try{
        URL url = new URL(strUrl);
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.connect();
        iStream = urlConnection.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
        StringBuffer sb  = new StringBuffer();
        String line = "";
        while( ( line = br.readLine())  != null){
            sb.append(line);
        }
        data = sb.toString();
        br.close();
    }catch(Exception e){
    }finally{
        iStream.close();
        urlConnection.disconnect();
    }
    return data;
}
private class DownloadTask extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... url) {
        String data = "";
        try{
            data = downloadUrl(url[0]);
        }catch(Exception e){
            Log.d("Background Task",e.toString());
        }
        return data;
    }
    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        ParserTask parserTask = new ParserTask();
        parserTask.execute(result);
    }
}
private class ParserTask extends AsyncTask<String, Integer, List<List<HashMap<String,String>>> >{
    @Override
    protected List<List<HashMap<String, String>>> doInBackground(String... jsonData) {
        JSONObject jObject;
        List<List<HashMap<String, String>>> routes = null;
        try{
            jObject = new JSONObject(jsonData[0]);
            DirectionsJSONParser parser = new DirectionsJSONParser();
            routes = parser.parse(jObject);
        }catch(Exception e){
            e.printStackTrace();
        }
        return routes;
    }
    @Override
    protected void onPostExecute(List<List<HashMap<String, String>>> result) {
        ArrayList<LatLng> points = null;
        PolylineOptions lineOptions = null;
        for(int i=0;i<result.size();i++){
            points = new ArrayList<LatLng>();
            lineOptions = new PolylineOptions();
            List<HashMap<String, String>> path = result.get(i);
            for(int j=0;j<path.size();j++){
                HashMap<String,String> point = path.get(j);
                double lat = Double.parseDouble(point.get("lat"));
                double lng = Double.parseDouble(point.get("lng"));
                LatLng position = new LatLng(lat, lng);
                points.add(position);
            }
            lineOptions.addAll(points);
            lineOptions.width(2);
            lineOptions.color(Color.RED);
        }
        mMap.addPolyline(lineOptions);
    }}
protected synchronized void buildGoogleApiClient() {
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();
    mGoogleApiClient.connect();}
@Override
public void onConnected(Bundle bundle) {
    mLocationRequest = new LocationRequest();
    mLocationRequest.setInterval(1000);
    mLocationRequest.setFastestInterval(1000);
    mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
    if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION)
            == PackageManager.PERMISSION_GRANTED) {
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
    }}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onLocationChanged(Location location) {
    mLastLocation = location;
    if (mCurrLocationMarker != null) {
        mCurrLocationMarker.remove();
    }
    LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
    MarkerOptions markerOptions = new MarkerOptions();
    markerOptions.position(latLng);
    markerOptions.title("Current Position");
    markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
    mCurrLocationMarker = mMap.addMarker(markerOptions);
    mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
    mMap.animateCamera(CameraUpdateFactory.zoomTo(11));
    if (mGoogleApiClient != null) {
        LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
    }}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
public boolean checkLocationPermission(){
    if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION)
            != PackageManager.PERMISSION_GRANTED) {
        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.ACCESS_FINE_LOCATION)) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                    MY_PERMISSIONS_REQUEST_LOCATION);
        } else {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                    MY_PERMISSIONS_REQUEST_LOCATION);}
        return false;} else {
        return true;
    }}
@Override
public void onRequestPermissionsResult(int requestCode,
                                       String permissions[], int[] grantResults) {
    switch (requestCode) {
        case MY_PERMISSIONS_REQUEST_LOCATION: {
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                if (ContextCompat.checkSelfPermission(this,
                        Manifest.permission.ACCESS_FINE_LOCATION)
                        == PackageManager.PERMISSION_GRANTED) {
                    if (mGoogleApiClient == null) {
                        buildGoogleApiClient();}
                    mMap.setMyLocationEnabled(true);}
            } else {
                Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
            }
            return;}}}}

2 个答案:

答案 0 :(得分:0)

如果你是否处于碎片状态并不重要。您应该像使用FusedLocationProviderApi

那样以任何其他方式获取当前位置

答案 1 :(得分:0)

您需要从活动中获取您的位置,一旦您获得该位置,您就会将其发送到您的片段。 但是如果您正在寻找Location API样本,请查看它。 点击Sample

我希望它对你有用。 祝你好运!!