SQlite Getting nearest locations (with latitude and longitude)

后端 未结 5 672
無奈伤痛
無奈伤痛 2020-11-22 05:54

I have data with latitude and longitude stored in my SQLite database, and I want to get the nearest locations to the parameters I put in (ex. My current location - lat/lng,

5条回答
  •  爱一瞬间的悲伤
    2020-11-22 06:39

    Try something like this:

        //locations to calculate difference with 
        Location me   = new Location(""); 
        Location dest = new Location(""); 
    
        //set lat and long of comparison obj 
        me.setLatitude(_mLat); 
        me.setLongitude(_mLong); 
    
        //init to circumference of the Earth 
        float smallest = 40008000.0f; //m 
    
        //var to hold id of db element we want 
        Integer id = 0; 
    
        //step through results 
        while(_myCursor.moveToNext()){ 
    
            //set lat and long of destination obj 
            dest.setLatitude(_myCursor.getFloat(_myCursor.getColumnIndexOrThrow(DataBaseHelper._FIELD_LATITUDE))); 
            dest.setLongitude(_myCursor.getFloat(_myCursor.getColumnIndexOrThrow(DataBaseHelper._FIELD_LONGITUDE))); 
    
            //grab distance between me and the destination 
            float dist = me.distanceTo(dest); 
    
            //if this is the smallest dist so far 
            if(dist < smallest){ 
                //store it 
                smallest = dist; 
    
                //grab it's id 
                id = _myCursor.getInt(_myCursor.getColumnIndexOrThrow(DataBaseHelper._FIELD_ID)); 
            } 
        } 
    

    After this, id contains the item you want from the database so you can fetch it:

        //now we have traversed all the data, fetch the id of the closest event to us 
        _myCursor = _myDBHelper.fetchID(id); 
        _myCursor.moveToFirst(); 
    
        //get lat and long of nearest location to user, used to push out to map view 
        _mLatNearest  = _myCursor.getFloat(_myCursor.getColumnIndexOrThrow(DataBaseHelper._FIELD_LATITUDE)); 
        _mLongNearest = _myCursor.getFloat(_myCursor.getColumnIndexOrThrow(DataBaseHelper._FIELD_LONGITUDE)); 
    

    Hope that helps!

提交回复
热议问题