Android Google地图圆圈可点击

huangapple go评论118阅读模式
英文:

Android Google Map circle clickable

问题

我正在制作一个应用程序,用于在地图上跟踪冠状病毒,通过在受影响的国家周围绘制一个圆圈来实现。我已经绘制了这些圆圈,但我想要的是,当我点击任何一个圆圈时,它会显示一些数据。因此,我想要使圆圈可点击,当我点击任何一个圆圈时,它会在文本框中显示有关该国家的一些详细信息。以下是地图活动的代码:

private GoogleMap mMap;
SearchView searchView;

private static final String TAG = MapsActivity.class.getSimpleName();

@SuppressLint("ClickableViewAccessibility")
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);
    searchView = findViewById(R.id.search_location);

    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);

    searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String s) {
            String location = searchView.getQuery().toString();
            List<Address> addressList = null;

            if (location != null || !location.equals("")) {
                Geocoder geocoder = new Geocoder(MapsActivity.this);
                try {
                    addressList = geocoder.getFromLocationName(location, 1);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                Address address = addressList.get(0);
                LatLng latLng = new LatLng(address.getLatitude(), address.getLongitude());
                mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 6));
            }
            return false;
        }

        @Override
        public boolean onQueryTextChange(String s) {
            return false;
        }
    });
}

@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    // 设置缩放控制栏以进行放大和缩小
    mMap.getUiSettings().setZoomControlsEnabled(true);
    mMap.getUiSettings().setMyLocationButtonEnabled(true);
    mMap.getUiSettings().setMapToolbarEnabled(true);

    try {
        // 使用在原始资源文件中定义的JSON对象来自定义基本地图的样式。
        boolean success = googleMap.setMapStyle(
                MapStyleOptions.loadRawResourceStyle(
                        this, R.raw.style_json));

        if (!success) {
            Log.e(TAG, "Style parsing failed.");
        }
    } catch (Resources.NotFoundException e) {
        Log.e(TAG, "Can't find style. Error: ", e);
    }

    fetchData();
}

private void fetchData() {
    String url = "https://corona.lmao.ninja/v2/countries/";
    StringRequest request = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            try {
                JSONArray jsonArray = new JSONArray(response);
                for (int i = 0; i < jsonArray.length(); i++) {
                    Double radius;
                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                    Double population = jsonObject.getDouble("population");
                    Double cases = jsonObject.getDouble("cases");
                    JSONObject object = jsonObject.getJSONObject("countryInfo");
                    Double lat = object.getDouble("lat");
                    Double lng = object.getDouble("long");

                    Double zoomLevel = Double.valueOf(mMap.getCameraPosition().zoom);

                    radius = ((cases / population) * 100) * 500000;
                    if (radius <= 80000) {
                        radius = 150000d;
                    } else if (radius > 80000 && radius < 600000) {
                        radius = 300000d;
                    } else radius = 600000d;

                    CircleOptions circleOptions = new CircleOptions().strokeWidth(3f).center(new LatLng(lat, lng)).radius(radius * (zoomLevel / 9))
                            .strokeColor(Color.RED).fillColor(Color.argb(70, 150, 50, 50));;

                    Circle circle = mMap.addCircle(circleOptions);

                    // 在这里添加点击事件监听器来处理点击圆圈时的操作
                    circle.setTag(jsonObject.toString());
                    mMap.setOnCircleClickListener(new GoogleMap.OnCircleClickListener() {
                        @Override
                        public void onCircleClick(Circle circle) {
                            String countryData = circle.getTag().toString();
                            // 在这里处理显示国家详细信息的操作,例如在文本框中显示
                        }
                    });
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Toast.makeText(MapsActivity.this, error.getMessage(), Toast.LENGTH_SHORT).show();
        }
    });
    RequestQueue requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(request);
}

请注意,在上述代码中,我已经添加了点击事件监听器,以便在点击圆圈时处理显示国家详细信息的操作。您可以在相应的回调函数中添加代码来显示详细信息,例如在文本框中显示。

英文:

I am making an application to track corona virus on map by drawing a circle on the map around the affected countries.
I did that circles but what i want is when i click on any circle it shows some data.
So i want to make a circle clickable so when i click on any circle it shows some detail about that country in a text box.
This is the map Activity code:

private GoogleMap mMap;
SearchView searchView;
private static final String TAG = MapsActivity.class.getSimpleName();
@SuppressLint(&quot;ClickableViewAccessibility&quot;)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
searchView = findViewById(R.id.search_location);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String s) {
String location = searchView.getQuery().toString();
List&lt;Address&gt; addressList = null;
if (location != null || !location.equals(&quot;&quot;)){
Geocoder geocoder = new Geocoder(MapsActivity.this);
try {
addressList = geocoder.getFromLocationName(location, 1);
} catch (IOException e) {
e.printStackTrace();
}
Address address = addressList.get(0);
LatLng latLng = new LatLng(address.getLatitude(), address.getLongitude());
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 6));
}
return false;
}
@Override
public boolean onQueryTextChange(String s) {
return false;
}
});
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
//set zoom control bar to zoom in and zoom out
mMap.getUiSettings().setZoomControlsEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(true);
mMap.getUiSettings().setMapToolbarEnabled(true);
try{
// Customise the styling of the base map using a JSON object defined
// in a raw resource file.
boolean success = googleMap.setMapStyle(
MapStyleOptions.loadRawResourceStyle(
this, R.raw.style_json));
if (!success) {
Log.e(TAG, &quot;Style parsing failed.&quot;);
}
} catch (Resources.NotFoundException e) {
Log.e(TAG, &quot;Can&#39;t find style. Error: &quot;, e);
}
fetchData();
}
private void fetchData() {
String url = &quot;https://corona.lmao.ninja/v2/countries/&quot;;
StringRequest request = new StringRequest(Request.Method.GET, url, new Response.Listener&lt;String&gt;() {
@Override
public void onResponse(String response) {
try {
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i &lt; jsonArray.length(); i++) {
Double radius;
JSONObject jsonObject = jsonArray.getJSONObject(i);
//String countryName = jsonObject.getString(&quot;country&quot;);
Double population = jsonObject.getDouble(&quot;population&quot;);
Double cases = jsonObject.getDouble(&quot;cases&quot;);
JSONObject object = jsonObject.getJSONObject(&quot;countryInfo&quot;);
Double lat = object.getDouble(&quot;lat&quot;);
Double lng = object.getDouble(&quot;long&quot;);
Double zoomLevel = Double.valueOf(mMap.getCameraPosition().zoom);
radius = ((cases / population )* 100) * 500000;
if (radius &lt;= 80000) {
radius = 150000d;
}
else if (radius &gt; 80000 &amp;&amp; radius &lt; 600000){
radius = 300000d;
}
else radius = 600000d;
CircleOptions circleOptions= new CircleOptions().strokeWidth(3f).center(new LatLng(lat, lng)).radius(radius*(zoomLevel/9))
.strokeColor(Color.RED).fillColor(Color.argb(70, 150, 50, 50));;
Circle circle = mMap.addCircle(circleOptions);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MapsActivity.this, error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(request);
}

}

答案1

得分: 0

可以为地图定义一个监听器:

mMap.setOnCircleClickListener(...)

并使圆形可点击:

circleOptions.clickable(true)
英文:

You can define a listener for the map

mMap.setOnCircleClickListener(...)

And make circles clickable

circleOptions.clickable(true)

huangapple
  • 本文由 发表于 2020年8月8日 01:33:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/63306687.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定