地理位置谷歌地图v2

时间:2013-08-16 10:58:22

标签: java android google-maps

我正在使用Google地图V2来获取我当前的位置,并附带行程 我的手机连接到互联网和GPS工作,但结果令人失望 有时候我有:“不可用”,同时它给了我连接点的位置,而不是当前的 这是我的代码

public class ItineraryActivity extends Activity {

private static final LatLng Event_place = new LatLng(33.59648, -7.664723);
private static final LatLng MOUNTAIN_VIEW = new LatLng(37.4, -122.1);
static final LatLng HAMBURG = new LatLng(53.558, 9.927);
private GoogleMap map;
private LocationManager service;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.mapevent);
    findViewById(R.id.direction).setVisibility(View.INVISIBLE);
    map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map))
            .getMap();
    map.setMapType(GoogleMap.MAP_TYPE_NORMAL);

    Marker hamburg = map.addMarker(new MarkerOptions()
            .position(Event_place).title("Our event")
            .snippet("We are waiting for you .."));

    map.moveCamera(CameraUpdateFactory.newLatLngZoom(Event_place, 15));
    /** Geo */
    service = (LocationManager) getSystemService(LOCATION_SERVICE);
    boolean enabled = service
            .isProviderEnabled(LocationManager.GPS_PROVIDER);
    // Activer GPS
    if (!enabled) {
        Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
        startActivity(intent);
        Log.e("eeee", "law 3lem");

    } else {
        Log.e("eeee", "law ");
    }
    // **
    Criteria criteria = new Criteria();
    String provider = service.getBestProvider(criteria, false);
    Location location = service.getLastKnownLocation(provider);
    // Initialize the location fields
    if (location != null) {
        System.out.println("Provider " + provider + " has been selected.");
        onLocationChanged(location);
        new Routing(this, map, Color.BLACK).execute(
                new LatLng(location.getLatitude(), location.getLongitude()),
                Event_place);

    } else {
        Log.e("", "not available");
    }


}

public void onLocationChanged(Location location) {
    double lat = (double) (location.getLatitude());
    double lng = (double) (location.getLongitude());

    Log.e("lat + long", String.valueOf(lat) + " / " + String.valueOf(lng));

    map.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lat, lng),
            14));
    map.addMarker(new MarkerOptions()
            .position(new LatLng(lat, lng))
            .title("Vous êtes là")
            .snippet("Nous comptons sur votre présence ...")
            .icon(BitmapDescriptorFactory
                    .defaultMarker(BitmapDescriptorFactory.HUE_BLUE)));
    map.animateCamera(CameraUpdateFactory.zoomTo(14), 2000, null);
}

}

1 个答案:

答案 0 :(得分:1)

试试此代码

public class ItineraryActivity extends Activity implements LocationListener {

    public static final double A = 6372.8; // In kilometers
    private static final LatLng Event_place = new LatLng(33.59648, -7.664723);
    static final LatLng HAMBURG = new LatLng(53.558, 9.927);
    private GoogleMap map;
    private LocationManager service;
    private LocationManager locationManager;
    private String provider;
    Marker mark;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.mapevent);
        findViewById(R.id.direction).setVisibility(View.INVISIBLE);
        map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map))
                .getMap();
        map.setMapType(GoogleMap.MAP_TYPE_NORMAL);

        Marker hamburg = map.addMarker(new MarkerOptions()
                .position(Event_place).title("Our event")
                .snippet("We are waiting for you .."));

        map.moveCamera(CameraUpdateFactory.newLatLngZoom(Event_place, 15));
        /** Geo */
        service = (LocationManager) getSystemService(LOCATION_SERVICE);
        boolean enabledGPS = service
                .isProviderEnabled(LocationManager.GPS_PROVIDER);
        boolean enabledWiFi = service
                .isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        if (!enabledGPS) {
            Toast.makeText(this, "GPS signal not found", Toast.LENGTH_LONG)
                    .show();
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            startActivity(intent);
        }

        locationManager = (LocationManager) this
                .getSystemService(Context.LOCATION_SERVICE);

        //
        boolean enabled = service
                .isProviderEnabled(LocationManager.GPS_PROVIDER);
        // Activer GPS
        Criteria criteria = new Criteria();
        provider = locationManager.getBestProvider(criteria, false);
        Location location = locationManager.getLastKnownLocation(provider);

        // Initialize the location fields
        if (location != null) {
            Toast.makeText(this, "Selected Provider " + provider,
                    Toast.LENGTH_SHORT).show();
            onLocationChanged(location);

            new Routing(this, map, Color.BLACK)
                    .execute(
                            new LatLng(location.getLatitude(), location
                                    .getLongitude()), Event_place);
        } else {

            // do something
        }
        // Initialize the location fields

    }

    public void onLocationChanged(Location location) {

        // mark.remove();
        double lat = location.getLatitude();
        double lng = location.getLongitude();
        /*Toast.makeText(this, " Location " + lat + "," + lng, Toast.LENGTH_LONG)
                .show();*/
        LatLng coordinate = new LatLng(lat, lng);
        Toast.makeText(
                this,
                "Location "
                        + coordinate.latitude
                        + ","
                        + coordinate.longitude
                        + "\n Distance :"
                        + haversine(coordinate.latitude, coordinate.longitude,
                                Event_place.latitude, Event_place.longitude)
                        + "Km", Toast.LENGTH_LONG).show();

        Log.e("lat + long", String.valueOf(lat) + " / " + String.valueOf(lng));

        map.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lat, lng),
                14));
        if (mark != null) {

            mark.remove();
        }

        mark = map.addMarker(new MarkerOptions()
                .position(new LatLng(lat, lng))
                .title("Vous êtes là")
                .snippet("Nous comptons sur votre présence ...")
                .icon(BitmapDescriptorFactory
                        .defaultMarker(BitmapDescriptorFactory.HUE_BLUE)));

        map.animateCamera(CameraUpdateFactory.zoomTo(14), 2000, null);
    }

    @Override
    public void onProviderDisabled(String provider) {
        // TODO Auto-generated method stub
        Toast.makeText(this, "Enabled new provider " + provider,
                Toast.LENGTH_SHORT).show();

    }

    @Override
    public void onProviderEnabled(String provider) {
        // TODO Auto-generated method stub
        Toast.makeText(this, " Disabled provider " + provider,
                Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub

    }

    /* Request updates at startup */
    @Override
    protected void onResume() {
        super.onResume();
        locationManager.requestLocationUpdates(provider, 400, 10, this);
    }

    /* Remove the locationlistener updates when Activity is paused */
    @Override
    protected void onPause() {
        super.onPause();
        locationManager.removeUpdates(this);
    }

    public double haversine(double lat1, double lon1, double lat2, double lon2) {
        double dLat = Math.toRadians(lat2 - lat1);
        double dLon = Math.toRadians(lon2 - lon1);
        lat1 = Math.toRadians(lat1);
        lat2 = Math.toRadians(lat2);
        double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.sin(dLon / 2)
                * Math.sin(dLon / 2) * Math.cos(lat1) * Math.cos(lat2);
        double c = 2 * Math.asin(Math.sqrt(a));
        return A * c;
    }
}