做一些事情,当我圆半径内 [英] Do something when I'm inside radius of circle

查看:192
本文介绍了做一些事情,当我圆半径内的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用谷歌地图API。

我要的是,当我移动到了一些特定的位置,并有一个圆圈我已经在地图上绘制,将会进入到另一个活动。

因此​​,它是这样的:

  1. 我的立场是=(X,Y)

  2. 圆的位置是B =(X,Y)半径= 10

  3. 在我b半径内就会转到其他活动或做一些事情。

任何想法?

我已经使用 distanceTo(),但仍然没有成功。

编辑:这里是更新code,它仍然不是为我工作:

 公共无效onLocationChanged(位置定位)
{
浮动[]距离=新的浮动[];
Location.distanceBetween(location.getLatitude(),location.getLongitude(),-6.xxxxxxx,106.xxxxxxx,distance);

如果(距离[0]< 50)
   {
   意图I =新的意图(student_activity.this,indoor.class);
   student_activity.this,startActivity(ⅰ);
   }
}
 

此方法setUpMapIfNeeded()被调用onCreate方法:

 公共无效圆()
{
圈圈= mMap.addCircle(新CircleOptions()
.center(新经纬度(-6.xxxxxxx,106.xxxxxxx))
.radius(50)
.strokeColor(Color.RED)
.strokeWidth(1)
.fillColor(Color.RED)
}
 

解决方案

您可以使用地理围栏,但如果你只是想确定你的当前位置是绘制地图上的圆圈内,您可以使用这种技术。

只需从当前位置的距离比较圆的中心,并检查距离小于半径

我回答过类似的问题<一href="http://stackoverflow.com/questions/30170271/android-google-map-how-to-check-if-the-gps-location-is-inside-the-circle/30171471#30171471">here,在这里你可以看到更多信息和截图的例子。

请注意,code以下使用depricated <一href="http://developer.android.com/reference/com/google/android/gms/maps/GoogleMap.OnMyLocationChangeListener.html"相对=nofollow> onMyLocationChangeListener ,但你可以使用任何类型的位置,回调要做到这一点,包括FusedLocationProviderApi。

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

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

                如果(距离[0]&其中; mCircle.getRadius()){
                    //当前的位置是圆圈内
                    //启动新活动
                    意图I =新的意图(ThisActivity.this,OtherActivity.class);
                    ThisActivity.this.startActivity(ⅰ);
                }

            }
        });
 

编辑:这是一个使用FusedLocationApi获取当前位置充分的工作和测试类:

 进口android.content.Intent;
进口android.graphics.Color;
进口android.location.Location;
进口android.os.Bundle;
进口android.support.v7.app.ActionBarActivity;
进口android.util.Log;
进口android.widget.Toast;

进口com.google.android.gms.common.ConnectionResult;
进口com.google.android.gms.common.api.GoogleApiClient;
进口com.google.android.gms.location.LocationListener;
进口com.google.android.gms.location.LocationRequest;
进口com.google.android.gms.location.LocationServices;
进口com.google.android.gms.maps.CameraUpdateFactory;
进口com.google.android.gms.maps.GoogleMap;
进口com.google.android.gms.maps.SupportMapFragment;
进口com.google.android.gms.maps.model.Circle;
进口com.google.android.gms.maps.model.CircleOptions;
进口com.google.android.gms.maps.model.LatLng;
进口com.google.android.gms.maps.model.LatLngBounds;
进口com.google.android.gms.maps.model.MarkerOptions;

公共类MapsActivity扩展ActionBarActivity工具
        GoogleApiClient.ConnectionCallbacks,GoogleApiClient.OnConnectionFailedListener,LocationListener的{

    私人GoogleMap的MMAP;
    LocationRequest mLocationRequest;
    GoogleApiClient mGoogleApiClient;
    圈mCircle;

    @覆盖
    保护无效的onCreate(包savedInstanceState){
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.activity_maps);
        setUpMapIfNeeded();

        buildGoogleApiClient();
        mGoogleApiClient.connect();
    }

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

    @覆盖
    保护无效的onPause(){
        super.onPause();
        如果(mGoogleApiClient!= NULL){
            LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient,这一点);
        }
    }


    保护同步无效buildGoogleApiClient(){
        Toast.makeText(这一点,buildGoogleApiClient,Toast.LENGTH_SHORT).show();
        mGoogleApiClient =新GoogleApiClient.Builder(本)
                .addConnectionCallbacks(本)
                .addOnConnectionFailedListener(本)
                .addApi(LocationServices.API)
                。建立();
    }

    @覆盖
    公共无效onConnected(束捆){
        Toast.makeText(这一点,onConnected,Toast.LENGTH_SHORT).show();

        mLocationRequest =新LocationRequest();
        mLocationRequest.setInterval(10);
        mLocationRequest.setFastestInterval(10);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
        mLocationRequest.setSmallestDisplacement(0.1F);

        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,mLocationRequest,这一点);
    }


    私人无效setUpMapIfNeeded(){
        //做一个空检查确认,我们还没有实例化的地图。
        如果(MMAP == NULL){
            //尝试获取来自SupportMapFragment地图。
            MMAP =((SupportMapFragment)getSupportFragmentManager()。findFragmentById(R.id.map))
                    .getMap();
            //检查如果我们成功取得地图。
            如果(MMAP!= NULL){
                setUpMap();
            }
        }
    }

    私人无效setUpMap(){
        mMap.getUiSettings()setMapToolbarEnabled(真)。
        mMap.getUiSettings()setZoomControlsEnabled(真)。
        mMap.setMyLocationEnabled(真正的);

        圈();

    }

    公共无效圆()
    {
        双radiusInMeters = 50.0;
        INT则strokeColor = 0xFFFF0000地址; //红色轮廓
        INT shadeColor = 0x44ff0000; //不透明的红色填充

        mCircle = mMap.addCircle(新CircleOptions()
                .center(新经纬度(37.9614,-122.105))
                .radius(radiusInMeters)
                .fillColor(shadeColor)
                .strokeColor(则strokeColor)
                .strokeWidth(1));
    }

    @覆盖
    公共无效onConnectionSuspended(int i)以{
        Toast.makeText(这一点,onConnectionSuspended,Toast.LENGTH_SHORT).show();
    }

    @覆盖
    公共无效onConnectionFailed(ConnectionResult connectionResult){
        Toast.makeText(这一点,onConnectionFailed,Toast.LENGTH_SHORT).show();
    }

    @覆盖
    公共无效onLocationChanged(位置定位){

        Log.d(locationtesting,纬度:+ location.getLatitude()+离子:+ location.getLongitude());

        Toast.makeText(这一点,位置改变,Toast.LENGTH_SHORT).show();

        浮动[]距离=新的浮动[2];

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

        如果(距离[0]&其中; mCircle.getRadius()){
            //当前的位置是圆圈内
            //启动新活动
            意图I =新的意图(这一点,OtherActivity.class);
            startActivity(ⅰ);
        }
    }
}
 

布局的xml:

 &LT;片段的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
    的xmlns:工具=htt​​p://schemas.android.com/tool​​s机器人:layout_width =match_parent
    机器人:layout_height =match_parent机器人:ID =@ + ID /图工具:上下文=。MapsActivity
    机器人:名称=com.google.android.gms.maps.SupportMapFragment/&GT;
 

在build.gradle依赖关系:

 相关性{
    编译文件树(导演:库,包括:['的* .jar'])
    编译com.android.support:appcompat-v7:22.1.1
    编译com.google.android.gms:播放服务:7.0.0
}
 

首先,我做了一个测试,而不()调用 startActivity 只是为了确保我的当前位置是在圆内。正如你可以在截图中看到,它是:

然后,我添加了调用 startActivity() onLocationChanged()回调,并推出了 OtherActivity 启动应用程序之后。

I'm using Google Maps API.

What I want is when I move into some specific location and there is a circle I already have draw on the map, it will then go to another Activity.

So it was like :

  1. my position is a = (X,Y)

  2. Circle position is b = (X,Y) radius = 10

  3. When I'm inside b radius it will go to another Activity or do something.

Any ideas ?

I'm already using distanceTo(), but still haven't succeeded.

Edit: Here is updated code that still is not working for me:

public void onLocationChanged(Location location)
{
float [] distance = new float[];
Location.distanceBetween(location.getLatitude(),location.getLongitude(),-6.xxxxxxx,106.xxxxxxx,distance);

if (distance[0] < 50)
   {
   Intent i = new Intent(student_activity.this,indoor.class);
   student_activity.this,startActivity(i);
   }
}

This method setUpMapIfNeeded() is called in onCreate method :

public void circle()
{
Circle circle = mMap.addCircle (new CircleOptions()
.center(new LatLng(-6.xxxxxxx,106.xxxxxxx))
.radius(50)
.strokeColor(Color.RED)
.strokeWidth(1)
.fillColor(Color.RED)
}

解决方案

You could use geofencing, but if you are simply trying to determine if your current location is within a circle drawn on a map, you could use this technique.

Simply compare the distance from the current location to the center of the circle, and check if the distance is less than the radius.

I answered a similar question here, where you can see more info, and screenshot examples.

Note that the code below uses the depricated onMyLocationChangeListener, but you could use any type of location callback to do this, including FusedLocationProviderApi.

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

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

                if( distance[0] < mCircle.getRadius() ){
                    //current location is within circle
                    //start new activity
                    Intent i = new Intent(ThisActivity.this, OtherActivity.class);
                    ThisActivity.this.startActivity(i);
                }

            }
        });

Edit: Here is a fully working and tested class that uses the FusedLocationApi to get the current location:

import android.content.Intent;
import android.graphics.Color;
import android.location.Location;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.Circle;
import com.google.android.gms.maps.model.CircleOptions;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.MarkerOptions;

public class MapsActivity extends ActionBarActivity implements
        GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {

    private GoogleMap mMap;
    LocationRequest mLocationRequest;
    GoogleApiClient mGoogleApiClient;
    Circle mCircle;

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

        buildGoogleApiClient();
        mGoogleApiClient.connect();
    }

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

    @Override
    protected void onPause(){
        super.onPause();
        if (mGoogleApiClient != null) {
            LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
        }
    }


    protected synchronized void buildGoogleApiClient() {
        Toast.makeText(this,"buildGoogleApiClient",Toast.LENGTH_SHORT).show();
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
    }

    @Override
    public void onConnected(Bundle bundle) {
        Toast.makeText(this,"onConnected", Toast.LENGTH_SHORT).show();

        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(10);
        mLocationRequest.setFastestInterval(10);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
        mLocationRequest.setSmallestDisplacement(0.1F);

        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
    }


    private void setUpMapIfNeeded() {
        // Do a null check to confirm that we have not already instantiated the map.
        if (mMap == null) {
            // Try to obtain the map from the SupportMapFragment.
            mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
                    .getMap();
            // Check if we were successful in obtaining the map.
            if (mMap != null) {
                setUpMap();
            }
        }
    }

    private void setUpMap() {
        mMap.getUiSettings().setMapToolbarEnabled(true);
        mMap.getUiSettings().setZoomControlsEnabled(true);
        mMap.setMyLocationEnabled(true);

        circle();

    }

    public void circle()
    {
        double radiusInMeters = 50.0;
        int strokeColor = 0xffff0000; //red outline
        int shadeColor = 0x44ff0000; //opaque red fill

        mCircle = mMap.addCircle (new CircleOptions()
                .center(new LatLng(37.9614, -122.105))
                .radius(radiusInMeters)
                .fillColor(shadeColor)
                .strokeColor(strokeColor)
                .strokeWidth(1));
    }

    @Override
    public void onConnectionSuspended(int i) {
        Toast.makeText(this,"onConnectionSuspended",Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        Toast.makeText(this,"onConnectionFailed",Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onLocationChanged(Location location) {

        Log.d("locationtesting",  "lat: " + location.getLatitude() + " lon: " + location.getLongitude());

        Toast.makeText(this,"Location Changed",Toast.LENGTH_SHORT).show();

        float[] distance = new float[2];

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

        if( distance[0] < mCircle.getRadius() ){
            //current location is within circle
            //start new activity
            Intent i = new Intent(this, OtherActivity.class);
            startActivity(i);
        }
    }
}

Layout xml:

<fragment xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:id="@+id/map" tools:context=".MapsActivity"
    android:name="com.google.android.gms.maps.SupportMapFragment" />

Dependencies in build.gradle:

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:22.1.1'
    compile 'com.google.android.gms:play-services:7.0.0'
}

First I did a test without the call to startActivity() just to make sure that my current location was within the circle. As you can see in the screenshot, it was:

Then, I added the call to startActivity() in the onLocationChanged() callback, and it launched OtherActivity immediately after launching the app.

这篇关于做一些事情,当我圆半径内的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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