2017-01-17 3 views
-2

Wir bekommen den Code in Aktivität.Aber nicht in der Lage zu implementieren in Fragment.Hier ist der Code in Aktivität.Bitte helfen Sie uns, den aktuellen Speicherort in Fragment zu finden. Wir sind in der Lage, Marker in Fragmente zu setzen, aber wir sind nicht in der Lage, den aktuellen Ort in Fragment zu bekommen. Bitte helfen Sie uns, wie wir eine Anwendung tun, die sich mit Karten beschäftigt.Karte aktuellen Ort in Fragment

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;}}}} 
+0

Was ist das Problem? beschreiben in mehr Details mit Code –

+0

wir versuchen, aktuelle Position in Fragment zu bekommen. Wir sind in Aktivität, aber nicht in der Lage zu integrieren in das Fragment – Arya

+0

OK also, was ist das Problem, das Sie in Fragment konfrontiert? –

Antwort

0

Es spielt keine Rolle, ob Sie in Fragment oder nicht sind. Sie sollten den aktuellen Standort wie jeden anderen Weg erhalten, z. B. FusedLocationProviderApi

+0

Aber wie mit FusedLocationProviderApi zu implementieren, können Sie bitte mit dem Code bereitstellen – Arya

0

Sie müssen Ihren Standort von Ihrer Aktivität abrufen und sobald Sie den Speicherort erhalten, werden Sie es an Ihr Fragment senden. Aber wenn Sie nach Location API Beispiel suchen, dann schauen Sie es sich an. Klicken Sie Sample

Ich hoffe, es wird für Sie arbeiten. Viel Glück !!

Verwandte Themen