android - 仅显示 10 公里内靠近我当前位置的位置

标签 android json google-maps android-maps-v2

在我的程序中,我使用JSON Web 服务在 map 上显示多个标记,但现在我只想显示位置接近我当前的位置,例如 10 公里以内

所以在这里我想知道如何显示最近的标记,而不是显示所有标记!

我正在放置我用来在 Map V2

上放置标记的整个代码
public class MainActivity extends FragmentActivity implements LocationListener {

    private static final String LOG_TAG = "JsOn ErRoR";

    private static final String SERVICE_URL = " ";

    protected GoogleMap mapB;

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

     // Getting Google Play availability status
        int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());

        // Showing status
        if(status!=ConnectionResult.SUCCESS){ // Google Play Services are not available

            int requestCode = 10;
            Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
            dialog.show();

        }else { // Google Play Services are available   

            // Getting reference to the SupportMapFragment of activity_main.xml
            SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);

            // Getting GoogleMap object from the fragment
            mapB = fm.getMap();

            // Enabling MyLocation Layer of Google Map
            mapB.setMyLocationEnabled(true); 

             // Getting LocationManager object from System Service LOCATION_SERVICE
            LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

            // Creating a criteria object to retrieve provider
            Criteria criteria = new Criteria();

            // Getting the name of the best provider
            String provider = locationManager.getBestProvider(criteria, true);

            // Getting Current Location
            Location location = locationManager.getLastKnownLocation(provider);

            if(location!=null){
                    onLocationChanged(location);
            }

            locationManager.requestLocationUpdates(provider, 20000, 0, this);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        setUpMapIfNeeded();
    }

    private void setUpMapIfNeeded() {
        if (mapB == null) {
            mapB = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
                    .getMap();
            if (mapB != null) {
                setUpMap();
            }
        }
    }

    private void setUpMap() {

        new Thread(new Runnable() {
            public void run() {
                try {
                    retrieveAndAddCities();
                } catch (IOException e) {
                    Log.e(LOG_TAG, "Cannot retrive cities", e);
                    return;
                }
            }
        }).start();
    }

    protected void retrieveAndAddCities() throws IOException {
        HttpURLConnection conn = null;
        final StringBuilder json = new StringBuilder();
        try {
            // Connect to the web service
            URL url = new URL(SERVICE_URL);
            conn = (HttpURLConnection) url.openConnection();
            InputStreamReader in = new InputStreamReader(conn.getInputStream());

            // Read the JSON data into the StringBuilder
            int read;
            char[] buff = new char[1024];
            while ((read = in.read(buff)) != -1) {
                json.append(buff, 0, read);
            }
        } catch (IOException e) {
            Log.e(LOG_TAG, "Error connecting to service", e);
            throw new IOException("Error connecting to service", e);
        } finally {
            if (conn != null) {
                conn.disconnect();
            }
        }

        // Must run this on the UI thread since it's a UI operation.
        runOnUiThread(new Runnable() {
            public void run() {
                try {
                    createMarkersFromJson(json.toString());
                } catch (JSONException e) {
                    Log.e(LOG_TAG, "Error processing JSON", e);
                }
            }
        });
    }

    void createMarkersFromJson(String json) throws JSONException {

        JSONArray jsonArray = new JSONArray(json);
        System.out.print(json);
        List<Marker> markers = new ArrayList<Marker>();

        for (int i = 0; i < jsonArray.length(); i++) {

            JSONObject jsonObj = jsonArray.getJSONObject(i);
            System.out.print(jsonObj.getJSONArray("latlng"));
            Marker marker = mapB.addMarker(new MarkerOptions()
                .title(jsonObj.getString("business_name"))
                .position(new LatLng(
                        jsonObj.getJSONArray("latlng").getDouble(0),
                        jsonObj.getJSONArray("latlng").getDouble(1)))
                        .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN))
            );
            markers.add(marker);
        }
    }

    @Override
    public void onLocationChanged(Location location) {
        // Getting latitude of the current location
        double latitude = location.getLatitude();

        // Getting longitude of the current location
        double longitude = location.getLongitude();     

        // Creating a LatLng object for the current location
        LatLng latLng = new LatLng(latitude, longitude);

        // Showing the current location in Google Map
        mapB.moveCamera(CameraUpdateFactory.newLatLng(latLng));

        // Zoom in the Google Map
        mapB.animateCamera(CameraUpdateFactory.zoomTo(15));

    }

    @Override
    public void onProviderDisabled(String provider) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onProviderEnabled(String provider) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub

    }
}

我的 JSON 看起来像:-

[
{
"business_name":"Connaught Place",
"latlng":
[
"28.632777800000000000",
"77.219722199999980000"
]
},
{
"business_name":"Moolchand",
"latlng":
[
"28.568927000000000000",
"77.235073000000060000"
]
}
]

最佳答案

获取您当前的位置。遍历位置,确定到每个位置的距离(使用 Location.distanceBetween 来计算它)。按距离对位置进行排序。然后只将 N 个最近的标记添加到您的 map 。

关于android - 仅显示 10 公里内靠近我当前位置的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23671955/

相关文章:

java - 如何以编程方式在布局中居中进度条?

android - 我是否应该担心内存泄漏以及在 Android 中将 WeakReference 与 Volley 结合使用

java - JSON 到 Java 对象的 TestNG 测试类中的编译错误

.net - JSON 序列化需要很长时间

json - ElasticSearch 中的范围查询(GET without body)

android - 同步Gradle失败

javascript - 谷歌地图圆半径适合 map

javascript - 谷歌地图每次都无法在 map 上放置一些标记

具有谷歌地图 View 的 iOS 应用程序未触发 TouchEnded :withEvent: method

java - Android - 如何从光标中删除项目?