【问题标题】:My location coordinates in android我在android中的位置坐标
【发布时间】:2014-04-03 11:58:16
【问题描述】:

我试图从 gps 坐标中获取我当前的位置。我看到了很多我应该如何做到这一点的例子。当我尝试将我的代码与示例代码合并时,我在这一行得到一个错误:

lm.requestLocationUpdates(provider, 1, 0, locationListener);

它说:

The method requestLocationUpdates(String, long, float, LocationListener) in the type LocationManager is not applicable for the arguments (String, int, int, LocationListener)

哪里可能有问题..?花几个小时寻找问题..

public class MyLocationDemoActivity extends FragmentActivity implements
        ConnectionCallbacks,
        OnConnectionFailedListener, 
        LocationListener,
        OnMyLocationButtonClickListener{
    GMapV2Direction md;
    private GoogleMap mMap;
    GeoPoint gp;
    private LocationClient mLocationClient;
    LocationManager lm;
    private TextView mMessageView;
    Bundle extras;
    Location mycurrent;
    LatLng endpoint;
    Location mCurrentLocation;
    static double currentlatid;
    static double currentlonid;

    private static final LocationRequest REQUEST = LocationRequest.create()
            .setInterval(16000) // 16 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();


        lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

        locationListener = new MyLocationListener();
        Criteria criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_FINE);
        String provider = lm.getBestProvider(criteria, true);
        Location mostRecentLocation = lm.getLastKnownLocation(provider);
        if(mostRecentLocation != null) {
            currentlatid=mostRecentLocation.getLatitude();
            currentlonid=mostRecentLocation.getLongitude();
        }
        lm.requestLocationUpdates(provider, 1, 0, locationListener);

        extras = getIntent().getExtras();

        LatLng a = null;
        try {
            a = (LatLng) extras.get("coord");
        } catch (Exception x) {
        }
        if (a == null) {
            try {

                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");
        endpoint = b;
        draw_route(a, b);
        }catch(Exception e){

        }

        LatLng c = null;
        try {
            c = (LatLng) extras.get("Obj2");
            endpoint = c;
            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");
            endpoint = d;
            draw_route(c, d);

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

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

        try{
            mMap.setMyLocationEnabled(true);
            mMap.setOnMyLocationButtonClickListener(this);
        }catch(Exception e ){

        }


    }

    // }

    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);
        Toast.makeText(this, "MyLocation button clicked", 50000000)
        .show();
        draw_route(new LatLng(location.getLatitude(), location.getLongitude()), endpoint);
    }

    /**
     * Callback called when connected to GCore. Implementation of
     * {@link ConnectionCallbacks}.
     */
    @Override
    public void onConnected(Bundle connectionHint) {
        mLocationClient.requestLocationUpdates(REQUEST, this); // LocationListener
        mCurrentLocation = mLocationClient.getLastLocation();
         System.out.println("@@@@@@@@@@@@@\n"+mCurrentLocation+"\n@@2222222@@@@@@@@@@@``");
    }

    /**
     * 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;
    }
    class MyLocationListener implements LocationListener {

        @Override
        public void onLocationChanged(Location loc) {
          if (loc != null) {
              currentlatid = loc.getLatitude();
            currentlonid = loc.getLongitude();

            float accuracyd = loc.getAccuracy();
            String providershown = loc.getProvider();    



           }
        }
}}

【问题讨论】:

  • 看我的回答!!!检查你的进口

标签: android gps location maps


【解决方案1】:

android 中有两个 LocationListener 类

1. android.location.LocationListener
2. com.google.android.gms.location.LocationListener

确保您通过了第一个。只需检查您的导入语句,它必须是android.location.LocationListener

【讨论】:

  • @danny117 对手已经接受了我的回答,并且已经解决了他的问题,你可以清楚地看到问题在于,正如我在回答中给出的那样,那么你怎么能说下一个答案是正确的。解释一下你的问题正在考虑这个问题。我认为你也给这个答案的其他观众提供了错误的方向。
  • @danny117 你真的认为这个答案是错误的吗?此答案适用于“user3416113”的具体问题。
  • 修正你答案中的语法,我会投票给你。我认为它没有错,我认为以下答案更好。我的意思是用户需要做的就是通过在常量后面添加一个 f 来将常量作为浮点数传递,以告诉编译器该常量是一个浮点数来修复他的错误。
  • @danny117 如果您显示任何语法错误,您可以编辑我的答案。你不能投票反对这个问题,因为只有语法错误它违反了这个网站的政策,是的,我已经根据对手的问题给出了正确的答案,下一个答案不是你可以清楚地看到的对手问题的解决方案。我认为你应该再读一遍对手的问题,这样你就知道对手在问什么。如果你认为我的回答是错误的,你可以什么,但我提醒你对手已经接受了我的回答,谢谢。
  • 我投了赞成票。还是喜欢下面的答案。祝你有美好的一天。
【解决方案2】:

基于 LocationManager 类的文档,方法 requestLocationUpdates 需要以下参数

    requestLocationUpdates(String provider, long minTime, float minDistance, LocationListener listener)

在您的情况下,您传递给方法的 minTime 类型是 int 类型。此外,minDistance 的类型也是 int。

您需要将 minTime 更改为 long 并将 minDistance 更改为 float。您可以使用以下代码执行此操作:

     long minTime = (long)1; 
     float minDistance = (float)0; 

然后您可以按如下方式调用 requestLocationUpdates:

     lm.requestLocationUpdates(provider, 1, 0, locationListener);

这应该可以解决您的问题。

【讨论】:

  • long minTime=1;浮动最小距离=0;不需要在你的编辑器中进行检查
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-14
  • 2016-09-19
  • 2013-05-29
  • 1970-01-01
相关资源
最近更新 更多