我目前的位置LatLng

时间:2014-04-03 08:27:05

标签: android google-maps

我写了一个课程,当我按下按钮时获取我当前的位置,并从其他课程获得其他积分来绘制路线。如果我没有通过我当前的位置地址,它应该获取我当前的位置,并从当前位置绘制路线。 我无法找到获取当前位置LatLng的方法。我怎么能得到它? 这是我的班级: 顺便说一下,我是android编程的新手,所以代码不是很好YET:)

public class MyLocationDemoActivity extends FragmentActivity implements
        ConnectionCallbacks, OnConnectionFailedListener, LocationListener,
        OnMyLocationButtonClickListener {
    GMapV2Direction md;
    private GoogleMap mMap;
    GeoPoint gp;
    private LocationClient mLocationClient;
    private TextView mMessageView;
    Bundle extras;
    Location mycurrent;
    // These settings are the same as the settings for the map. They will in
    // fact give you updates
    // at the maximal rates currently possible.
    private static final LocationRequest REQUEST = LocationRequest.create()
            .setInterval(5000) // 5 seconds
            .setFastestInterval(16) // 16ms = 60fps
            .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.my_location_demo);
        Intent intent = getIntent();
        RouteActivity route = new RouteActivity();
        // if (route.myAddress.isEmpty()) {
        // System.out.println(" 60 line ");
        // } else {
        // mMap = ((SupportMapFragment) getSupportFragmentManager()
        // .findFragmentById(R.id.map)).getMap();
        extras = getIntent().getExtras();
        LatLng a = null;
        try {
            a = (LatLng) extras.get("coord");
        } catch (Exception x) {
        }
        if (a == null) {
            try {
                System.out.println();
                /*//if (mLocationClient != null && mLocationClient.isConnected()) {
                LocationManager locManager;

                locManager =(LocationManager)getSystemService(Context.LOCATION_SERVICE);
                                //idetas
                locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000L,
                    500.0f, locationListener);
                Location location = locManager
                        .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                if (location != null) {
                    double latitude = location.getLatitude();
                    double longitude = location.getLongitude();
                }
                */
                //}
                LatLng x = new LatLng(mycurrent.getLatitude(),
                        mycurrent.getLongitude());
                a = x;
                System.out.print(a);
            } catch (Exception x) {

            }

            System.out.print(a);
        }
        LatLng b ;
        try{
        b = (LatLng) extras.get("Obj1");

        draw_route(a, b);
        }catch(Exception e){

        }

        LatLng c = null;
        try {
            c = (LatLng) extras.get("Obj2");
            b = (LatLng) extras.get("Obj1");
            draw_route(b, c);

        } catch (Exception e) {
            System.out.println("smth went wrong");
        }
        try {
            LatLng d = (LatLng) extras.get("Obj3");

            draw_route(c, d);

        } catch (Exception e) {
            System.out.println("smth went wrong");
        }

        // mMap.addMarker(new MarkerOptions().position(a));

        mMap.setMyLocationEnabled(true);
        mMap.setOnMyLocationButtonClickListener(this);

        // }
        // if (!route.ObjLoc1String.isEmpty()) {

    }

    // }

    private final LocationListener locationListener = new LocationListener() {

        public void onLocationChanged(Location location) {
            updateWithNewLocation(location);
        }

        public void onProviderDisabled(String provider) {
            updateWithNewLocation(null);
        }

        public void onProviderEnabled(String provider) {}

        public void onStatusChanged(String provider,int status,Bundle extras){}
    };
    private void updateWithNewLocation(Location location) {
       // TextView myLocationText = (TextView) findViewById(R.id.text);
        String latLongString = "";
        if (location != null) {
            double lat = location.getLatitude();
            double lng = location.getLongitude();
            latLongString = "Lat:" + lat + "\nLong:" + lng;
        } else {
            latLongString = "No location found";
        }
       // myLocationText.setText("Your Current Position is:\n" + latLongString);
    }
    private void setUpLocationClientIfNeeded() {
        if (mLocationClient == null) {
            mLocationClient = new LocationClient(getApplicationContext(), this, // ConnectionCallbacks
                    this); // OnConnectionFailedListener
        }
    }

    public void draw_route(LatLng start, LatLng finish) {
        if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
                    .permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }

        md = new GMapV2Direction();
        mMap = ((SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map)).getMap();

        LatLng coordinates = new LatLng(54.72, 25.3);
        mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(coordinates, 10));

        mMap.addMarker(new MarkerOptions().position(start).title("Start"));
        mMap.addMarker(new MarkerOptions().position(finish).title("End"));

        Document doc = md.getDocument(start, finish,
                GMapV2Direction.MODE_DRIVING);
        int duration = md.getDurationValue(doc);
        String distance = md.getDistanceText(doc);
        String start_address = md.getStartAddress(doc);
        String copy_right = md.getCopyRights(doc);

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

    /**
     * Button to get current Location. This demonstrates how to get the current
     * Location as required without needing to register a LocationListener.
     */
    public void showMyLocation(View view) {
        if (mLocationClient != null && mLocationClient.isConnected()) {
            String msg = "Location = " + mLocationClient.getLastLocation();
            Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT)
                    .show();
            mycurrent = mLocationClient.getLastLocation();
        }
    }

    /**
     * Implementation of {@link LocationListener}.
     */
    @Override
    public void onLocationChanged(Location location) {
        mMessageView.setText("Location = " + location);
    }

    /**
     * Callback called when connected to GCore. Implementation of
     * {@link ConnectionCallbacks}.
     */
    @Override
    public void onConnected(Bundle connectionHint) {
        mLocationClient.requestLocationUpdates(REQUEST, this); // LocationListener
    }

    /**
     * Callback called when disconnected from GCore. Implementation of
     * {@link ConnectionCallbacks}.
     */
    @Override
    public void onDisconnected() {
        // Do nothing
    }

    /**
     * Implementation of {@link OnConnectionFailedListener}.
     */
    @Override
    public void onConnectionFailed(ConnectionResult result) {
        // Do nothing
    }

    @Override
    public boolean onMyLocationButtonClick() {
        Toast.makeText(this, "MyLocation button clicked", Toast.LENGTH_SHORT)
                .show();
        // Return false so that we don't consume the event and the default
        // behavior still occurs
        // (the camera animates to the user's current position).
        return false;
    }
}

1 个答案:

答案 0 :(得分:0)

public void onLocationChanged(Location location) {
    mMessageView.setText("Location = " + location);
    draw_route(new LatLng(location.getLatitude(), location.getLongitude()), new LatLng( ... point where should be the end of route ...));
}

我不知道我是否理解正确,但似乎你应该调用draw_route并从传递给onLocationChanged事件的位置获取LatLng。这是起点。此外,您有一些终点作为LatLng作为第二个参数传递给draw_route。在绘制路线中,如果您想获得正确的路线,请使用传递的参数坐标使用Google方向服务,并在接收数据后,您将获得路线中的所有点,并且您还可以绘制正确的折线。