发送和获取位置数据

时间:2016-02-04 11:34:48

标签: android

我有一个应用程序,其当前位置显示在地图上。现在我想将该位置发送到localhost服务器,所以我已经这样做了。

@Override
public void onMapReady(GoogleMap googleMap) {
    Toast.makeText(this, "fffff", Toast.LENGTH_LONG).show();
    mMap = googleMap;

    try {


        // String bp=lm.getBestProvider(new Criteria(),true);


        String bestprovider = lm.getBestProvider(new Criteria(), true);
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

            return;
        }
        Location l = lm.getLastKnownLocation(bestprovider);


        double lat = l.getLatitude();
        double lng = l.getLongitude();


        Toast.makeText(this, "" + lat + lng, Toast.LENGTH_LONG).show();
        LatLng ll = new LatLng(lat, lng);

        Geocoder gc = new Geocoder(this);
        List<Address> Al = gc.getFromLocation(lat, lng, 1);
          //send to  server

        // Create a new HttpClient and Post Header
        HttpClient httpclient = new DefaultHttpClient();
        HttpGet htget = new HttpGet("http://10.0.2.2/loc.php?lat="+la+"&lng="+lo);

        try {
            // Execute HTTP Post Request
            HttpResponse response = httpclient.execute(htget);
            String resp = response.getStatusLine().toString();
            Toast.makeText(this, resp, Toast.LENGTH_LONG).show();


        } catch (ClientProtocolException e) {
            Toast.makeText(this, "Error", Toast.LENGTH_LONG).show();
        } catch (IOException e) {
            Toast.makeText(this, "Error", Toast.LENGTH_LONG).show();
        }








        String result;
        result = Al.get(0).getAddressLine(0) + ", " + Al.get(0).getAddressLine(1) + ", " + Al.get(0).getAddressLine(2) + ", " + Al.get(0).getAddressLine(3) + ", " + "lat=" + Al.get(0).getLatitude() + ", " + "lng=" + Al.get(0).getLongitude();
        Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();


        mMap.addMarker(new MarkerOptions().position(ll).draggable(true).title("Current Location"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(ll));
        mMap.animateCamera(CameraUpdateFactory.zoomTo(15));


    } catch (Exception e) {


        Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();

    }
}

我正在使用这个php文件将数据发送到数据库。我正在用html测试这个php,它给了我一个无法解析的错误。

<?php
$lat=$_GET['lat'];
$lng=$_GET['lng'];

$com=$_mysql("localhost","root","","images");
$sql="insert into MyLoc values('$lat','$lng');
$_mysql($com,$sql);
 <?php

这不起作用。请更正我的代码。如果可能的话,也让我知道如何从另一个应用程序获取这些数据。我是开发新手。只是一个初学者。提前谢谢。

1 个答案:

答案 0 :(得分:0)

你有NetworkOnMainThreadException。清楚地显示在IDE的LogCat中。首先寻找它,因为它可以为你和我们节省很多时间,如果你马上提到的那样。您必须将http网络代码放在AsyncTask或线程中。