百度地图系列05——显示屏幕范围内的marker

百度地图系列05——显示屏幕范围内的marker

原理:根据屏幕中心点坐标和屏幕的长宽计算出屏幕左上角和右下角坐标,然后判断所显示的marker是否在这个范围内。

中心点坐标:

        LatLng mCenterLatLng = status.target;

        double lat = mCenterLatLng.latitude;
        double lng = mCenterLatLng.longitude;

屏幕的宽度和高度:

        WindowManager wm = this.getWindowManager();
        //这种方法已被淘汰
//      int width = wm.getDefaultDisplay().getWidth();
//      int height = wm.getDefaultDisplay().getHeight();

        DisplayMetrics outMetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(outMetrics);
        int width = outMetrics.widthPixels;
        int height = outMetrics.heightPixels;

左上角经纬度:

        Point pt = new Point();
        pt.x = 0;
        pt.y = 0;
        LatLng ll = mBaiduMap.getProjection().fromScreenLocation(pt);

右下角经纬度:

        Point ptr = new Point();
        ptr.x = width;
        ptr.y = height;
        LatLng llr = mBaiduMap.getProjection().fromScreenLocation(ptr);

判断是否在屏幕范围内并添加marker:

if(ll_right.latitude<lat&&lat<ll_left.latitude&&ll_left.longitude<lng&&lng<ll_right.longitude){
                        LatLng ll_pt = new LatLng(lat, lng);
                        Log.i("this is", lat+","+lng);
                        BitmapDescriptor bitmap = BitmapDescriptorFactory.fromResource(R.drawable.icon_gcoding);
//                      MarkerOptions markerOption = new MarkerOptions().icon(bitmap).position(ll_pt);
                        OverlayOptions options = new MarkerOptions()
                        .position(ll_pt)
                        .icon(bitmap)
                        .zIndex(12)
                        .draggable(true);
                        marker = (Marker) mBaiduMap.addOverlay(options);
}                                   

用的baiduapi如下图所示:
百度地图系列05——显示屏幕范围内的marker_第1张图片

完整代码,里面还包括定位代码:

package com.yds.newpowerbike.activity;


import java.util.ArrayList;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BaiduMap.OnMapStatusChangeListener;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.yds.newpowerbike.R;
import com.yds.newpowerbike.bean.PolePoint;
import com.yds.newpowerbike.net.ConnectServerIml;
import com.yds.newpowerbike.net.ShareData;
import com.yds.newpowerbike.util.JsonParse;

import android.app.Activity;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Point;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.WindowManager;

public class ConcernAct extends Activity{
    private MapView mMapView;

    private LocationClient mLocClient;
    public MyLocationListener1 myListener1 = new MyLocationListener1();;

    BaiduMap mBaiduMap;
    boolean isLocationClientStop = false;
    boolean isFirstLoc = true;
    ArrayList<String>PoleName,PoleAddress,PoleFix;
    ConnectServerIml iml;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        SDKInitializer.initialize(getApplicationContext());
        setContentView(R.layout.activity_concern);
        mMapView = (MapView) findViewById(R.id.concern_map);
        mBaiduMap = mMapView.getMap();
        mBaiduMap.setMyLocationEnabled(true);

        mLocClient = new LocationClient(this);
        mLocClient.registerLocationListener(myListener1);
        LocationClientOption option = new LocationClientOption();
        option.setIsNeedAddress(true);
        option.setOpenGps(true);
        option.setCoorType("bd09ll");
        option.setScanSpan(1000);
        mLocClient.setLocOption(option);
        mLocClient.start();
        mBaiduMap.setOnMapStatusChangeListener(new OnMapStatusChangeListener() {

            @Override
            public void onMapStatusChangeStart(MapStatus arg0) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onMapStatusChangeFinish(MapStatus status) {
                // TODO Auto-generated method stub
                updateMapState(status);
            }

            @Override
            public void onMapStatusChange(MapStatus arg0) {
                // TODO Auto-generated method stub

            }
        });

    }
    private void updateMapState(MapStatus status){
        LatLng mCenterLatLng = status.target;

        double lat = mCenterLatLng.latitude;
        double lng = mCenterLatLng.longitude;
        Log.i("中心点坐标", lat+","+lng);

        WindowManager wm = this.getWindowManager();
//      int width = wm.getDefaultDisplay().getWidth();
//      int height = wm.getDefaultDisplay().getHeight();

        DisplayMetrics outMetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(outMetrics);
        int width = outMetrics.widthPixels;
        int height = outMetrics.heightPixels;

        Log.i("屏幕宽度和高度", width+","+height);

        Point pt = new Point();
        pt.x = 0;
        pt.y = 0;
        LatLng ll = mBaiduMap.getProjection().fromScreenLocation(pt);
        Log.i("左上角经纬度", ll.latitude+","+ll.longitude);

        Point ptr = new Point();
        ptr.x = width;
        ptr.y = height;
        LatLng llr = mBaiduMap.getProjection().fromScreenLocation(ptr);
        Log.i("右下角经纬度", llr.latitude+","+llr.longitude);
        SharedPreferences shared = getSharedPreferences("point", 0);
        Editor editor = shared.edit();
        editor.putString("leftPointx", String.valueOf(ll.latitude));
        editor.putString("leftPointy", String.valueOf(ll.longitude));
        editor.putString("rightPointx", String.valueOf(llr.latitude));
        editor.putString("rightPointy", String.valueOf(llr.longitude));
        editor.commit();
//      if (!shared.getString("cityName", "null").equals("")) {
//          Log.i("cityName", shared.getString("cityName", "null"));
//      }
        //这里是从服务器端获取坐标点,这里你们可以自定义坐标点
        new Thread(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub

                String url = ShareData.CHARGE_SEARCH;
                iml = new ConnectServerIml();
                String result = iml.ConcernByClientGet(url);
                ArrayList<PolePoint>list = JsonParse.search(result);
                PolePoint pp;
                PoleName = new ArrayList<String>();
                PoleAddress = new ArrayList<String>();
                PoleFix = new ArrayList<String>();
                for (int i = 0; i < list.size(); i++) {
                    pp = list.get(i);
                    PoleName.add(pp.getPoleName());
                    PoleAddress.add(pp.getPoleAdress());
                    PoleFix.add(pp.getPoleFix());
                }
                Bundle bundle = new Bundle();
                Message msg = new Message();
                msg.what = 0x01;
                bundle.putStringArrayList("PoleName", PoleName);
                bundle.putStringArrayList("PoleAddress", PoleAddress);
                bundle.putStringArrayList("PoleFix", PoleFix);
                msg.setData(bundle);
                handler.sendMessage(msg);
            }
        }).start();

    }
    Handler handler = new Handler(){
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg.what==0x01){
                SharedPreferences shared = getSharedPreferences("point", 0);
                LatLng ll_left = new LatLng(Double.valueOf(shared.getString("leftPointx", "")),
                        Double.valueOf(shared.getString("leftPointy", "")));
                LatLng ll_right = new LatLng(Double.valueOf(shared.getString("rightPointx", "")),
                        Double.valueOf(shared.getString("rightPointy", "")));
                Marker marker;

                for(int i = 0;i<msg.getData().getStringArrayList("PoleFix").size();i++){
                    iml = new ConnectServerIml();
                    String pt = msg.getData().getStringArrayList("PoleFix").get(i);

                    double lat = iml.getLat(pt);
                    double lng = iml.getLng(pt);
//                  Log.i("Tag", lat+","+lng);
                    Log.i("this is", ll_right.latitude+","+ll_left.latitude);
                    if(ll_right.latitude<lat&&lat<ll_left.latitude&&ll_left.longitude<lng&&lng<ll_right.longitude){
                        LatLng ll_pt = new LatLng(lat, lng);
                        Log.i("this is", lat+","+lng);
                        BitmapDescriptor bitmap = BitmapDescriptorFactory.fromResource(R.drawable.icon_gcoding);
//                      MarkerOptions markerOption = new MarkerOptions().icon(bitmap).position(ll_pt);
                        OverlayOptions options = new MarkerOptions()
                        .position(ll_pt)
                        .icon(bitmap)
                        .zIndex(12)
                        .draggable(true);
                        marker = (Marker) mBaiduMap.addOverlay(options);


                    }
                }


            }
        };
    };
    public class MyLocationListener1 implements BDLocationListener{

        @Override
        public void onReceiveLocation(BDLocation location) {
            // TODO Auto-generated method stub
            if(location == null||isLocationClientStop)
                return;
            MyLocationData locData = new MyLocationData.Builder()
            .accuracy(location.getRadius())
            .direction(100)
            .latitude(location.getLatitude())
            .longitude(location.getLongitude())
            .build();
            mBaiduMap.setMyLocationData(locData);
            if(isFirstLoc){
                isFirstLoc = false;
                LatLng ll = new LatLng(location.getLatitude(),
                        location.getLongitude());
                MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(ll);
                mBaiduMap.animateMapStatus(u);

            }
            SharedPreferences shared = getSharedPreferences("city", 0);
            Editor editor = shared.edit();
            String city = location.getCity()+"this";
            if(!city.equals("this")){
                editor.putString("cityName", location.getCity());
                editor.commit();
            }
        }


    }
    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
//      mLocClient.stop();
//      mBaiduMap.setMyLocationEnabled(false);
//      mMapView = null;
        mMapView.onDestroy();
        super.onDestroy();
    }
    @Override
    public void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        mMapView.onPause();
    }
    @Override
    public void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        mMapView.onResume();
    }

}

运行截图:
百度地图系列05——显示屏幕范围内的marker_第2张图片

因为涉及项目原因,而且重新写一个比较烦,所以这里就不给源码下载了,以后或许会补上。

你可能感兴趣的:(baidumap)