如何从另一个班级拿走LatLng?

时间:2016-07-25 04:21:32

标签: android

因为我将使用put extra从其他类中获取数据。如何从其他课程中获得经度和纬度的价值。我试过以下代码:

 package com.example.khoir.emegency_service;

 Bundle extras =getIntent().getExtras();
 Double lat1=Double.valueOf(extras.getString("lt1"));
 Double lg1=Double.valueOf(extras.getString("lg2"));

 LatLng fromPosition = new LatLng(lat1, lg1);
 LatLng toPosition = new LatLng(-7.8032857, 110.3738408);


 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);

    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync((OnMapReadyCallback) this);


    if (android.os.Build.VERSION.SDK_INT > 9) {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
    }

    md = new GMapV2Direction();
    mMap = ((MapFragment) getFragmentManager()
            .findFragmentById(R.id.map)).getMap();

    LatLng coordinates = new LatLng(-7.8032857, 110.3738408);
    mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(coordinates, 16));


    mMap.addMarker(new MarkerOptions().position(fromPosition).title("Start"));
    mMap.addMarker(new MarkerOptions().position(toPosition).title("End"));

    Document doc = md.getDocument(fromPosition, toPosition, GMapV2Direction.MODE_WALKING);


    ArrayList<LatLng> directionPoint = md.getDirection(doc);
    PolylineOptions rectLine = new PolylineOptions().width(3).color(Color.RED);

    for (int i = 0; i < directionPoint.size(); i++) {
        rectLine.add(directionPoint.get(i));
    }

    mMap.addPolyline(rectLine);
    mMap.getUiSettings().setZoomControlsEnabled(true);
    if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.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;
    }
    mMap.setMyLocationEnabled(true);


}

package com.example.khoir.emegency_service;
DialogInterface.OnClickListener listener;

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

    Button go = (Button) findViewById(R.id.button1);
    go.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Intent i = new Intent(MainActivity.this, Main_Pemadam_Kebakaran.class);
            startActivity(i);
        }
    });

    Button kul = (Button) findViewById(R.id.button2);
    kul.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Intent i = new Intent(MainActivity.this, MainRumahSakit.class);
            startActivity(i);
        }
    });



    final Button maps = (Button) findViewById(R.id.button4);
    maps.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {



            Intent i = new Intent(MainActivity.this, MapsActivity.class);
            i.putExtra("lt1",""+"-7.8013823");
            i.putExtra("lg1",""+"110.3647725");





            startActivity(i);
        }
    });
    Button peng = (Button) findViewById(R.id.button3);
    peng.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Intent i = new Intent(MainActivity.this, MainPolisi.class);
            startActivity(i);
        }
    });
    Button tent = (Button) findViewById(R.id.button5);
    tent.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Intent i = new Intent(MainActivity.this, Tentang.class);
            startActivity(i);
        }
    });

    Button twit= (Button) findViewById(R.id.btntwitter);
    twit.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Intent i = new Intent(MainActivity.this, twitter.class);
            startActivity(i);
        }
    });

    final LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("Aplikasi Memerlukan Akses GPS, GPS Anda Belum Aktif, Buka Setting Dan Aktifkan GPS?")
                .setCancelable(false)
                .setPositiveButton("Ya", new DialogInterface.OnClickListener() {
                    public void onClick(@SuppressWarnings("unused") final DialogInterface dialog, @SuppressWarnings("unused") final int id) {
                        startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
                    }
                })
                .setNegativeButton("Tidak", new DialogInterface.OnClickListener() {
                    public void onClick(final DialogInterface dialog, @SuppressWarnings("unused") final int id) {
                        dialog.cancel();
                    }
                });
        final AlertDialog alert = builder.create();
        alert.show();
    } else {
        Toast.makeText(getApplicationContext(), "GPS Sudah Aktif", Toast.LENGTH_LONG).show();
    }
}

public boolean onKeyDown(int keyCode, KeyEvent event) {
    //jika tombol BACK ditekan
    if (keyCode == KeyEvent.KEYCODE_BACK) {
        Keluar();
    }
    return super.onKeyDown(keyCode, event);
}

//method untuk keluar aplikasi menggunakan dialog terlebih dahulu
private void Keluar() {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage("Apakah Anda Yakin Ingin Keluar?");
    builder.setCancelable(false);//tombol BACK tidak bisa tekan

    //Membuat listener untuk tombol DIALOG
    listener = new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            if (which == DialogInterface.BUTTON_POSITIVE) {
                finish(); //keluar aplikasi
            } else if (which == DialogInterface.BUTTON_NEGATIVE) {
                dialog.cancel(); //batal keluar
            }
        }
    };

    //menerapkan listener pada tombol ya dan tidak
    builder.setPositiveButton("Ya", listener);
    builder.setNegativeButton("Tidak", listener);
    builder.show(); //menampilkan dialog


}

3 个答案:

答案 0 :(得分:0)

在第一个活动中,您以字符串形式发送值而不是“Bundle”。 所以在第二个活动中使用像

      String lat1=getIntent().getStringExtra("lat1");
 String lat1=getIntent().getStringExtra("lat2");

然后转换为double。

答案 1 :(得分:0)

你可以像这样发送latLng: -            intent.putExtra( “” keyname1" ,LAT);            intent.putExtra( “” keyname2" ,LNG);

在接收器类: -               Double lat = ggetIntent()。getDoubleExtra(“keyname1”,默认值);               Double lng = ggetIntent()。getDoubleExtra(“keyname2”,默认值);

答案 2 :(得分:0)

我没有得到错误,但尝试这对我有用....

    double latitude =26.8006704 ;
double longitude =75.7965136;
// Google Map
private GoogleMap googleMap;

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

    try {
        // Loading map
        initilizeMap();

    } catch (Exception e) {
        e.printStackTrace();
    }
}
/**
 * function to load map. If map is not created it will create it for you
 * */
private void initilizeMap() 
{
    if (googleMap == null) 
    {
        //getting a reference of GoogleMap class 
       FragmentManager fm=(FragmentManager)getFragmentManager();
       MapFragment mf =(MapFragment)fm.findFragmentById(R.id.map);
       googleMap =mf.getMap();
          //displaying  current location on the map
          googleMap.setMyLocationEnabled(true); // false to disable
          //set map type
            googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
          //googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
         // googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
        //  googleMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
        //  googleMap.setMapType(GoogleMap.MAP_TYPE_NONE);


          // create add marker on the map
          MarkerOptions marker = new MarkerOptions();
          LatLng latlan=new LatLng(latitude, longitude);
          marker.position(latlan);
          marker.title("City name");
          // adding marker
          googleMap.addMarker(marker);   
          //to change the marker color
          BitmapDescriptor discriptor=BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED);
          marker.icon(discriptor);


          //Moving Camera to a Location with animation
          CameraPosition cameraPosition = new CameraPosition.Builder().target(new LatLng(latitude,longitude)).zoom(9).build();

  googleMap.animateCamera(CameraUpdateFactory.
  newCameraPosition(cameraPosition));}}