doutui2016 2019-02-15 11:32
浏览 42
已采纳

列表靠近数据库Android的地方

i have a table with list of places am using php with (constant coordinates as the users location) to get the nearest place to the user in json and passing it to android recycler view. What am asking is if its possible to get the users location from android and get the nearest place from the db thanks for your help

Getting the nearest place

    <?php
require("dbdetails.php");
// Get parameters from URL


$center_lat = "0.2941146";
$center_lng = "32.5580577";
$radius = "25";

// Opens a connection to a mySQL server
$connection = mysql_connect ('localhost', $username, $password);
if (!$connection) {
  die("Not connected : " . mysql_error());
}
// Set the active mySQL database
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
  die ("Can\'t use db : " . mysql_error());
}
// Search the rows in the markers table
$query = sprintf("SELECT
  id,name,phone, (
    3959 * acos (
      cos ( radians(0.2941146) )
      * cos( radians( lat ) )
      * cos( radians( lng ) - radians(32.5580577) )
      + sin ( radians(0.2941146) )
      * sin( radians( lat ) )
    )
  ) AS distance
FROM markers
HAVING distance < 30
ORDER BY distance
LIMIT 0 , 20;");


$result = mysql_query($query);

if (!$result) {
  die("Invalid query: " . mysql_error());
}

$dbdata =  array();
// Iterate through the rows, adding XML nodes for each
while ($row = @mysql_fetch_assoc($result)){

$dbdata[]=$row;

}
//Print array in JSON format
$locs = json_encode($dbdata);

 file_put_contents('nearestlocations.json', $locs);
?>

Near by places Adapter to pass the result into android

public class NearestLocationAdapter extends RecyclerView.Adapter<NearestLocationAdapter.ViewHolder> {

    private Context context;
    private List<NearestLocation> listofnearestlocations;


    public NearestLocationAdapter(Context context, List<NearestLocation> listofnearestlocations) {
        this.context = context;
        this.listofnearestlocations = listofnearestlocations;
    }

    @NonNull
    @Override
    public NearestLocationAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View v = LayoutInflater.from(context).inflate(R.layout.single_item, viewGroup, false);
        return new ViewHolder(v);
    }

    @Override
    public void onBindViewHolder(@NonNull NearestLocationAdapter.ViewHolder viewHolder, int i) {

        NearestLocation nerbylocation = listofnearestlocations.get(i);
        viewHolder.textHospital.setText(nerbylocation.getName());
        viewHolder.textNumber.setText(nerbylocation.getPhone());
        viewHolder.textDistance.setText(nerbylocation.getDistance());

    }

    @Override
    public int getItemCount() {
        return listofnearestlocations.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {

        public TextView textHospital, textNumber, textDistance;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);

            textHospital = itemView.findViewById(R.id.locationname);
            textNumber = itemView.findViewById(R.id.locationphone);
            textDistance = itemView.findViewById(R.id.locationdistance);
        }
    }
}

Adding the result to android

  public class NearestLocationActivity extends AppCompatActivity {
    private String url = "http://192.168.43.163/prep/nearestlocations.json";

    private RecyclerView mList;

    private LinearLayoutManager linearLayoutManager;
    private DividerItemDecoration dividerItemDecoration;
    private List<NearestLocation> nearList;
    private RecyclerView.Adapter adapter;

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

        mList = findViewById(R.id.main_list);

        nearList = new ArrayList<>();
        adapter = new NearestLocationAdapter(getApplicationContext(),nearList);

        linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        dividerItemDecoration = new DividerItemDecoration(mList.getContext(), linearLayoutManager.getOrientation());

        mList.setHasFixedSize(true);
        mList.setLayoutManager(linearLayoutManager);
        mList.addItemDecoration(dividerItemDecoration);
        mList.setAdapter(adapter);

        getData();
    }

    private void getData() {
        final ProgressDialog progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("Loading...");
        progressDialog.show();

        JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
            @Override
            public void onResponse(JSONArray response) {
                for (int i = 0; i < response.length(); i++) {
                    try {
                        JSONObject jsonObject = response.getJSONObject(i);

                        NearestLocation nearestLocation = new NearestLocation();
                        nearestLocation.setName(jsonObject.getString("name"));
                        nearestLocation.setPhone(jsonObject.getInt("phone"));
                        nearestLocation.setDistance(jsonObject.getInt("distance"));

                        nearList.add(nearestLocation);
                    } catch (JSONException e) {
                        e.printStackTrace();
                        progressDialog.dismiss();
                    }
                }
                adapter.notifyDataSetChanged();
                progressDialog.dismiss();
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e("Volley", error.toString());
                progressDialog.dismiss();
            }
        });
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(jsonArrayRequest);
    }
}
  • 写回答

2条回答 默认 最新

  • dousong5161 2019-02-15 11:43
    关注

    Try this

        Location locationA = new Location("point A");
        locationA.setLatitude(lat);
        locationA.setLongitude(lng);
        Location locationB = new Location("point B");
        locationB.setLatitude(lat);
        locationB.setLongitude(lng);
        double distance = locationA.distanceTo(locationB);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛