Android的谷歌地图如何检查GPS位置的圆圈内 [英] Android Google Map how to check if the gps location is inside the circle

查看:640
本文介绍了Android的谷歌地图如何检查GPS位置的圆圈内的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想检测如果用户是一个标记的半径,使用用户的GPS位置。我有标记的坐标,但不知道如何计算该用户是否是在该地区。我试着用以下,但即使在当前位置是圈子里面我不断收到外部的消息。

 公共类MapaEscola扩展FragmentActivity {

    私人GoogleMap的GoogleMap的;
    私有序列化escolas;
    私人ProgressDialog对话框;
    私人圈mCircle;
    私人标记mMarker;



    @TargetApi(Build.VERSION_ codeS.ICE_CREAM_SANDWICH)
    @覆盖
    保护无效的onCreate(包savedInstanceState){
        super.onCreate(savedInstanceState);

        getActionBar()setDisplayHomeAsUpEnabled(真)。
        getActionBar()setHomeButtonEnabled(真)。

        的setContentView(R.layout.maps);

        //载入地图
        initilizeMap();

        //更改地图类型
        googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);

        //显示/隐藏您的当前位置
        googleMap.setMyLocationEnabled(真正的);

        //启用/禁用变焦控制
        googleMap.getUiSettings()setZoomControlsEnabled(真)。

        //启用/禁用我的位置按钮
        googleMap.getUiSettings()setMyLocationButtonEnabled(真)。

        //启用/禁用罗盘图标
        googleMap.getUiSettings()setCompassEnabled(真)。

        //启用/禁用旋转手势
        googleMap.getUiSettings()setRotateGesturesEnabled(真)。

        //启用/禁用变焦功能
        googleMap.getUiSettings()setZoomGesturesEnabled(真)。

        捆绑额外= getIntent()getBundleExtra(额外)。
        ArrayList的< Escolas>对象=(ArrayList的< Escolas>)extra.getSerializable(阵列);


        尝试 {

            的for(int i = 0; I< objects.size();我++){
                的System.out.println(escolas+ objects.get(ⅰ).getLatitude()++ objects.get(ⅰ).getLongitude());

                浮纬度= objects.get(我).getLatitude();
                浮经度= objects.get(ⅰ).getLongitude();

                googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(新经纬度(-23.316281,-51.155528),15));

                MarkerOptions选项=新MarkerOptions();

                //设置标记的位置

                options.position(新经纬度(纬度,经度));

                使用GoogleMap =((MapFragment)getFragmentManager()findFragmentById(R.id.map)。)的GetMap()。

                经纬度经纬度=新的经纬度(纬度,经度);
                drawMarkerWithCircle(经纬度);


                googleMap.setOnMyLocationChangeListener(新GoogleMap.OnMyLocationChangeListener(){
                    @覆盖
                    公共无效onMyLocationChange(位置定位){
                        浮动[]距离=新的浮动[2];

                        Location.distanceBetween(mMarker.getPosition(),纬度,mMarker.getPosition()。经度,
                                。mCircle.getCenter()纬度,mCircle.getCenter()经度,距离);

                        如果(距离[0]≥(mCircle.getRadius()/ 2)){
                            Toast.makeText(getBaseContext(),外,Toast.LENGTH_LONG).show();
                        } 其他 {
                            Toast.makeText(getBaseContext(),内部,Toast.LENGTH_LONG).show();
                        }

                    }
                });




            }



        }赶上(例外五){
            e.printStackTrace();
        }
    }


    私人无效drawMarkerWithCircle(经纬度位置){
        双radiusInMeters = 500.0;
        INT则strokeColor = 0xFFFF0000地址; //红色轮廓
        INT shadeColor = 0x44ff0000; //不透明的红色填充

        CircleOptions circleOptions =新CircleOptions().center(position).radius(radiusInMeters).fillColor(shadeColor).strokeColor(strokeColor).strokeWidth(8);
        mCircle = googleMap.addCircle(circleOptions);

        MarkerOptions markerOptions =新MarkerOptions()位置(位置)。
        mMarker = googleMap.addMarker(markerOptions);
    }



    私人无效initilizeMap(){

        如果(GoogleMap的== NULL){
            GoogleMap的=((MapFragment)getFragmentManager()。findFragmentById(
                    R.id.map))的GetMap()。

            //如果映射成功与否创建检查
            如果(GoogleMap的== NULL){
                Toast.makeText(getApplicationContext(),
                        NAO FOIpossívelcarregarØ地图,Toast.LENGTH_SHORT)
                        。显示();
            }
        }
    }

    @TargetApi(Build.VERSION_ codeS.HONEYCOMB)
    @覆盖
    公共无效onBack pressed(){

        super.onBack pressed();
        完();

    }

    @覆盖
    公共布尔onCreateOptionsMenu(功能菜单){
        // TODO自动生成方法存根
        MenuInflater充气= getMenuInflater();
        inflater.inflate(R.menu.menu_main,菜单);

        返回super.onCreateOptionsMenu(菜单);
    }

    @TargetApi(Build.VERSION_ codeS.HONEYCOMB)
    公共布尔onOptionsItemSelected(菜单项项){


        开关(item.getItemId()){

            案例android.R.id.home:
                super.onBack pressed();
                完();

                返回true;


        }

        返回true;

    }

    @覆盖
    保护无效onResume(){
        super.onResume();
        initilizeMap();
    }


}
 

解决方案

我刚刚运行的更新code和计算出的主要问题是什么。

您应该使用位置传入 onMyLocationChange()回调,以便它使用您的当前位置说,如果该设备是在圆内或不:

  googleMap.setOnMyLocationChangeListener(新GoogleMap.OnMyLocationChangeListener(){
                @覆盖
                公共无效onMyLocationChange(位置定位){
                    浮动[]距离=新的浮动[2];

                    / *
                    Location.distanceBetween(mMarker.getPosition(),纬度,mMarker.getPosition()。经度,
                            。mCircle.getCenter()纬度,mCircle.getCenter()经度,距离);
                            * /

                    Location.distanceBetween(location.getLatitude(),location.getLongitude(),
                            。mCircle.getCenter()纬度,mCircle.getCenter()经度,距离);

                    如果(距离[0]≥mCircle.getRadius()){
                        Toast.makeText(getBaseContext(),外,距离中心:+距离[0] +半径:+ mCircle.getRadius(),Toast.LENGTH_LONG).show();
                    } 其他 {
                        Toast.makeText(getBaseContext(),内部,距离中心:+距离[0] +半径:+ mCircle.getRadius(),Toast.LENGTH_LONG).show();
                    }

                }
            });
 

下面是我跑了全面工作的例子,它是你原来的code一个削减下来的版本:

 公共类MainActivity扩展ActionBarActivity {

    私人GoogleMap的GoogleMap的;
    私有序列化escolas;
    私人ProgressDialog对话框;
    私人圈mCircle;
    私人标记mMarker;



    @TargetApi(Build.VERSION_ codeS.ICE_CREAM_SANDWICH)
    @覆盖
    保护无效的onCreate(包savedInstanceState){
        super.onCreate(savedInstanceState);

        getSupportActionBar()setDisplayHomeAsUpEnabled(真)。
        getSupportActionBar()setHomeButtonEnabled(真)。

        的setContentView(R.layout.activity_main);

        //载入地图
        initilizeMap();

        //更改地图类型
        googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);

        //显示/隐藏您的当前位置
        googleMap.setMyLocationEnabled(真正的);

        //启用/禁用变焦控制
        googleMap.getUiSettings()setZoomControlsEnabled(真)。

        //启用/禁用我的位置按钮
        googleMap.getUiSettings()setMyLocationButtonEnabled(真)。

        //启用/禁用罗盘图标
        googleMap.getUiSettings()setCompassEnabled(真)。

        //启用/禁用旋转手势
        googleMap.getUiSettings()setRotateGesturesEnabled(真)。

        //启用/禁用变焦功能
        googleMap.getUiSettings()setZoomGesturesEnabled(真)。

       //捆绑额外= getIntent()getBundleExtra(额外)。
        // ArrayList的< Escolas>对象=(ArrayList的< Escolas>)extra.getSerializable(阵列);


        尝试 {
               //测试外
               双mLatitude = 37.77657;
               双mLongitude = -122.417506;


                //测试里面
                //双mLatitude = 37.7795516;
                //双mLongitude = -122.39292;


                googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(新经纬度(mLatitude,mLongitude),15));

                MarkerOptions选项=新MarkerOptions();

                //设置标记的位置

                options.position(新经纬度(mLatitude,mLongitude));

                //使用GoogleMap =((SupportMapFragment)getSupportFragmentManager()findFragmentById(R.id.map)。)的GetMap()。

                经纬度经纬度=新的经纬度(mLatitude,mLongitude);
                drawMarkerWithCircle(经纬度);


                googleMap.setOnMyLocationChangeListener(新GoogleMap.OnMyLocationChangeListener(){
                    @覆盖
                    公共无效onMyLocationChange(位置定位){
                        浮动[]距离=新的浮动[2];

                        / *
                        Location.distanceBetween(mMarker.getPosition(),纬度,mMarker.getPosition()。经度,
                                。mCircle.getCenter()纬度,mCircle.getCenter()经度,距离);
                                * /

                        Location.distanceBetween(location.getLatitude(),location.getLongitude(),
                                。mCircle.getCenter()纬度,mCircle.getCenter()经度,距离);

                        如果(距离[0]≥mCircle.getRadius()){
                            Toast.makeText(getBaseContext(),外,距离中心:+距离[0] +半径:+ mCircle.getRadius(),Toast.LENGTH_LONG).show();
                        } 其他 {
                            Toast.makeText(getBaseContext(),内部,距离中心:+距离[0] +半径:+ mCircle.getRadius(),Toast.LENGTH_LONG).show();
                        }

                    }
                });




        }赶上(例外五){
            e.printStackTrace();
        }
    }


    私人无效drawMarkerWithCircle(经纬度位置){
        双radiusInMeters = 500.0;
        INT则strokeColor = 0xFFFF0000地址; //红色轮廓
        INT shadeColor = 0x44ff0000; //不透明的红色填充

        CircleOptions circleOptions =新CircleOptions().center(position).radius(radiusInMeters).fillColor(shadeColor).strokeColor(strokeColor).strokeWidth(8);
        mCircle = googleMap.addCircle(circleOptions);

        MarkerOptions markerOptions =新MarkerOptions()位置(位置)。
        mMarker = googleMap.addMarker(markerOptions);
    }



    私人无效initilizeMap(){

        如果(GoogleMap的== NULL){
            GoogleMap的=((SupportMapFragment)getSupportFragmentManager()。findFragmentById(
                    R.id.map))的GetMap()。

            //如果映射成功与否创建检查
            如果(GoogleMap的== NULL){
                Toast.makeText(getApplicationContext(),
                        NAO FOIpossívelcarregarØ地图,Toast.LENGTH_SHORT)
                        。显示();
            }
        }
    }

    @TargetApi(Build.VERSION_ codeS.HONEYCOMB)
    @覆盖
    公共无效onBack pressed(){

        super.onBack pressed();
        完();

    }

    @覆盖
    公共布尔onCreateOptionsMenu(功能菜单){
        // TODO自动生成方法存根
        MenuInflater充气= getMenuInflater();
        inflater.inflate(R.menu.menu_main,菜单);

        返回super.onCreateOptionsMenu(菜单);
    }

    @TargetApi(Build.VERSION_ codeS.HONEYCOMB)
    公共布尔onOptionsItemSelected(菜单项项){


        开关(item.getItemId()){

            案例android.R.id.home:
                super.onBack pressed();
                完();

                返回true;


        }

        返回true;

    }

    @覆盖
    保护无效onResume(){
        super.onResume();
        initilizeMap();
    }


}
 

在圆的结果:

外循环的结果:

I'm trying to detect if a user is in the radius of a Marker , using the users gps location. I have the marker's coordinates, but do not know how to calculate whether the user is in the area. I've tried to use the following, but even when the current location is inside the circle I keep getting "outside" message.

public class MapaEscola extends FragmentActivity {

    private GoogleMap googleMap;
    private Serializable escolas;
    private ProgressDialog dialog;
    private Circle mCircle;
    private Marker mMarker;



    @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        getActionBar().setDisplayHomeAsUpEnabled(true);
        getActionBar().setHomeButtonEnabled(true);

        setContentView(R.layout.maps);

        // Loading map
        initilizeMap();

        // Changing map type
        googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);

        // Showing / hiding your current location
        googleMap.setMyLocationEnabled(true);

        // Enable / Disable zooming controls
        googleMap.getUiSettings().setZoomControlsEnabled(true);

        // Enable / Disable my location button
        googleMap.getUiSettings().setMyLocationButtonEnabled(true);

        // Enable / Disable Compass icon
        googleMap.getUiSettings().setCompassEnabled(true);

        // Enable / Disable Rotate gesture
        googleMap.getUiSettings().setRotateGesturesEnabled(true);

        // Enable / Disable zooming functionality
        googleMap.getUiSettings().setZoomGesturesEnabled(true);

        Bundle extra = getIntent().getBundleExtra("extra");
        ArrayList<Escolas> objects = (ArrayList<Escolas>) extra.getSerializable("array");


        try {

            for(int i = 0; i < objects.size(); i ++) {
                System.out.println(" escolas " + objects.get(i).getLatitude() + " " + objects.get(i).getLongitude());

                float latitude = objects.get(i).getLatitude();
                float longitude = objects.get(i).getLongitude();

                googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(-23.316281, -51.155528), 15));

                MarkerOptions options = new MarkerOptions();

                // Setting the position of the marker

                options.position(new LatLng(latitude, longitude));

                googleMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();

                LatLng latLng = new LatLng(latitude, longitude);
                drawMarkerWithCircle(latLng);


                googleMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
                    @Override
                    public void onMyLocationChange(Location location) {
                        float[] distance = new float[2];

                        Location.distanceBetween( mMarker.getPosition().latitude, mMarker.getPosition().longitude,
                                mCircle.getCenter().latitude, mCircle.getCenter().longitude, distance);

                        if( distance[0] > (mCircle.getRadius() / 2)  ){
                            Toast.makeText(getBaseContext(), "Outside", Toast.LENGTH_LONG).show();
                        } else {
                            Toast.makeText(getBaseContext(), "Inside", Toast.LENGTH_LONG).show();
                        }

                    }
                });




            }



        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private void drawMarkerWithCircle(LatLng position){
        double radiusInMeters = 500.0;
        int strokeColor = 0xffff0000; //red outline
        int shadeColor = 0x44ff0000; //opaque red fill

        CircleOptions circleOptions = new CircleOptions().center(position).radius(radiusInMeters).fillColor(shadeColor).strokeColor(strokeColor).strokeWidth(8);
        mCircle = googleMap.addCircle(circleOptions);

        MarkerOptions markerOptions = new MarkerOptions().position(position);
        mMarker = googleMap.addMarker(markerOptions);
    }



    private void initilizeMap() {

        if (googleMap == null) {
            googleMap = ((MapFragment) getFragmentManager().findFragmentById(
                    R.id.map)).getMap();

            // check if map is created successfully or not
            if (googleMap == null) {
                Toast.makeText(getApplicationContext(),
                        "Não foi possível carregar o mapa", Toast.LENGTH_SHORT)
                        .show();
            }
        }
    }

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    @Override
    public void onBackPressed() {

        super.onBackPressed();
        finish();

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // TODO Auto-generated method stub
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_main, menu);

        return super.onCreateOptionsMenu(menu);
    }

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    public boolean onOptionsItemSelected(MenuItem item) {


        switch (item.getItemId()) {

            case android.R.id.home:
                super.onBackPressed();
                finish();

                return true;


        }

        return true;

    }

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


}

解决方案

I just ran the updated code and figured out what the main problem is.

You should be using the Location passed into the onMyLocationChange() callback, so that it uses your current location to tell if the device is within the circle or not:

googleMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
                @Override
                public void onMyLocationChange(Location location) {
                    float[] distance = new float[2];

                    /*
                    Location.distanceBetween( mMarker.getPosition().latitude, mMarker.getPosition().longitude,
                            mCircle.getCenter().latitude, mCircle.getCenter().longitude, distance);
                            */

                    Location.distanceBetween( location.getLatitude(), location.getLongitude(),
                            mCircle.getCenter().latitude, mCircle.getCenter().longitude, distance);

                    if( distance[0] > mCircle.getRadius() ){
                        Toast.makeText(getBaseContext(), "Outside, distance from center: " + distance[0] + " radius: " + mCircle.getRadius(), Toast.LENGTH_LONG).show();
                    } else {
                        Toast.makeText(getBaseContext(), "Inside, distance from center: " + distance[0] + " radius: " + mCircle.getRadius() , Toast.LENGTH_LONG).show();
                    }

                }
            });

Here is the full working example that I ran, it's a pared down version of your original code:

public class MainActivity extends ActionBarActivity {

    private GoogleMap googleMap;
    private Serializable escolas;
    private ProgressDialog dialog;
    private Circle mCircle;
    private Marker mMarker;



    @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);

        setContentView(R.layout.activity_main);

        // Loading map
        initilizeMap();

        // Changing map type
        googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);

        // Showing / hiding your current location
        googleMap.setMyLocationEnabled(true);

        // Enable / Disable zooming controls
        googleMap.getUiSettings().setZoomControlsEnabled(true);

        // Enable / Disable my location button
        googleMap.getUiSettings().setMyLocationButtonEnabled(true);

        // Enable / Disable Compass icon
        googleMap.getUiSettings().setCompassEnabled(true);

        // Enable / Disable Rotate gesture
        googleMap.getUiSettings().setRotateGesturesEnabled(true);

        // Enable / Disable zooming functionality
        googleMap.getUiSettings().setZoomGesturesEnabled(true);

       // Bundle extra = getIntent().getBundleExtra("extra");
        //ArrayList<Escolas> objects = (ArrayList<Escolas>) extra.getSerializable("array");


        try {
               //test outside
               double mLatitude = 37.77657;
               double mLongitude = -122.417506;


                //test inside
                //double mLatitude = 37.7795516;
                //double mLongitude = -122.39292;


                googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(mLatitude, mLongitude), 15));

                MarkerOptions options = new MarkerOptions();

                // Setting the position of the marker

                options.position(new LatLng(mLatitude, mLongitude));

                //googleMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();

                LatLng latLng = new LatLng(mLatitude, mLongitude);
                drawMarkerWithCircle(latLng);


                googleMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
                    @Override
                    public void onMyLocationChange(Location location) {
                        float[] distance = new float[2];

                        /*
                        Location.distanceBetween( mMarker.getPosition().latitude, mMarker.getPosition().longitude,
                                mCircle.getCenter().latitude, mCircle.getCenter().longitude, distance);
                                */

                        Location.distanceBetween( location.getLatitude(), location.getLongitude(),
                                mCircle.getCenter().latitude, mCircle.getCenter().longitude, distance);

                        if( distance[0] > mCircle.getRadius()  ){
                            Toast.makeText(getBaseContext(), "Outside, distance from center: " + distance[0] + " radius: " + mCircle.getRadius(), Toast.LENGTH_LONG).show();
                        } else {
                            Toast.makeText(getBaseContext(), "Inside, distance from center: " + distance[0] + " radius: " + mCircle.getRadius() , Toast.LENGTH_LONG).show();
                        }

                    }
                });




        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private void drawMarkerWithCircle(LatLng position){
        double radiusInMeters = 500.0;
        int strokeColor = 0xffff0000; //red outline
        int shadeColor = 0x44ff0000; //opaque red fill

        CircleOptions circleOptions = new CircleOptions().center(position).radius(radiusInMeters).fillColor(shadeColor).strokeColor(strokeColor).strokeWidth(8);
        mCircle = googleMap.addCircle(circleOptions);

        MarkerOptions markerOptions = new MarkerOptions().position(position);
        mMarker = googleMap.addMarker(markerOptions);
    }



    private void initilizeMap() {

        if (googleMap == null) {
            googleMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(
                    R.id.map)).getMap();

            // check if map is created successfully or not
            if (googleMap == null) {
                Toast.makeText(getApplicationContext(),
                        "Não foi possível carregar o mapa", Toast.LENGTH_SHORT)
                        .show();
            }
        }
    }

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    @Override
    public void onBackPressed() {

        super.onBackPressed();
        finish();

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // TODO Auto-generated method stub
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_main, menu);

        return super.onCreateOptionsMenu(menu);
    }

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    public boolean onOptionsItemSelected(MenuItem item) {


        switch (item.getItemId()) {

            case android.R.id.home:
                super.onBackPressed();
                finish();

                return true;


        }

        return true;

    }

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


}

Results of Inside the circle:

Results of outside the circle:

这篇关于Android的谷歌地图如何检查GPS位置的圆圈内的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆