This article has participated in the activity of “New person creation Ceremony”, and started the road of digging gold creation together.

Due to the requirements of the project, polygons need to be drawn dynamically on the map, and whether a point is within the range of the polygon needs to be judged. According to the official demo and the materials checked online, the effect made is as follows:



The idea is: 1. Click the map to increase marker; 2. Get the marker and draw lines according to the marker (judge the number of points, when it is greater than 1); 3. Click marker to delete, and long press to drag; 4. When clicking OK, clear the line and draw the polygon (when the point is greater than 2); 5. Click on a point on the map and determine if it is in the polygon areaCopy the code

Step 1: Initialize the map and add listening events

  • Declare and initialize the variables needed
//marker related private marker marker; List<Marker> markers = new ArrayList<>(); Private List<String> ids = new ArrayList<>(); Private Map<String, LatLng> latlngs = new HashMap<>(); private InfoWindow mInfoWindow; // private Polyline mPolyline; // private Polygon Polygon; //private List<Polygon> polygons = new ArrayList<>(); private double latitude; private double longitude; Private int size; private int size; private int size; Private Map<String, Polygon> polygonMap = new HashMap<>(); Private List<String> AliasName = new ArrayList<>(); // private boolean polygonContainsPoint; List<String> areas = new ArrayList<>();Copy the code
map = (MapView) findViewById(R.id.map); baidumap = map.getMap(); / / to marker set the click event, which is used to delete marker baidumap. SetOnMarkerClickListener (this); / / to the map Settings to monitor events, click to get a map baidumap. The coordinates of the point of setOnMapClickListener (this); / / to marker set drag and drop to monitor events, used to obtain drag. After the completion of coordinate baidumap setOnMarkerDragListener (this);Copy the code
  • Click map listening event:
** @override public void onMapClick(latLng latLng) {toast.maketext (this, "coordinates are: " + latLng.latitude + ",,," + latLng.longitude, Toast.LENGTH_SHORT).show(); Log.e("aaa", "ditu d zuobiao is -->" + latLng.latitude + ",,," + latLng.longitude); // latitude = latLng. Latitude; longitude = latLng.longitude; // Add marker addMarler(latitude, longitude) to the map; if (ids.size() >= 2) { drawLine(); }}Copy the code
  • Marker click events on the map
@override public Boolean onMarkerClick(final marker marker) {Button button = new Button(getApplicationContext()); button.setBackgroundResource(R.drawable.popup); Button. The setText (" delete "); button.setTextColor(Color.BLACK); //button.setWidth(300); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { marker.remove(); String id1 = marker.getId(); ids.remove(id1); latlngs.remove(id1); Log.e("aaa", "delete map size--" + latlngs.size()); baidumap.hideInfoWindow(); if (ids.size() < 2) { if (mPolyline ! = null) { mPolyline.remove(); } return; } drawLine(); }}); LatLng ll = marker.getPosition(); mInfoWindow = new InfoWindow(button, ll, -50); baidumap.showInfoWindow(mInfoWindow); return true; }Copy the code
  • Monitor event for marker drag on map
@Override public void onMarkerDragEnd(Marker marker) { String id = marker.getId(); Log.e("aaa", "id-->" + id); double latitude1 = marker.getPosition().latitude; double longitude1 = marker.getPosition().longitude; Latlngs.remove (id); latlngs.remove(id); latlngs.put(id, new LatLng(latitude1, longitude1)); Toast.maketext (main2activity.this, "Tugging end, new location:" + latitude1 + ", "+ longitude1, toast.length_long).show(); The e (" aaa ", ids. The size () + "-- - the end of the drag and drop the map" + latlngs. The size ()); /* for (int i = 0; i < ids.size(); i++) { String s = ids.get(i); Log.e("aaa", "key= " + s + " and value= " + latlngs.get(s).toString()); }*/ / When the drag is complete, redraw the drawLine(); } @Override public boolean onMapPoiClick(MapPoi mapPoi) { return false; } @Override public void onMarkerDrag(Marker marker) { }Copy the code
  • The code for adding marker to the map is as follows:
/** * add marker ** @param longitude * @param longitude */ private void addMarler(double latitude, Double longitude) {// define Maker coordinates LatLng point = new LatLng(latitude, longitude); // Construct Marker descriptor BitmapDescriptor bitmap = bitmapDescriptorFactory.fromResource (r.rawable. Point); // Build MarkerOption, Marker OverlayOptions option = new MarkerOptions().position(point).icon(bitmap) //.zIndex(9).draggable(true);  // Add Marker to map and display Marker = (Marker) baidumap.addoverlay (option); markers.add(marker); String id = marker.getid (); latlngs.put(id, new LatLng(latitude, longitude)); ids.add(id); }Copy the code

Step 2: Draw a line

And the idea is, every time I add a point, I'm going to clear the line and redraw the line.Copy the code
Private void drawLine() {// If (mPolyline!) {// If (mPolyline! = null) { mPolyline.remove(); } List<LatLng> points = new ArrayList<LatLng>(); LatLng l = null; for (int i = 0; i < ids.size(); i++) { l = latlngs.get(ids.get(i)); points.add(l); } OverlayOptions ooPolyline = new PolylineOptions().width(10) .color(0xAAFF0000).points(points); mPolyline = (Polyline) baidumap.addOverlay(ooPolyline); }Copy the code

Step 3: Draw a polygon and add text in the center of the polygon

  • The first step is to determine whether the number of coordinate points matches
size = ids.size(); If (size <= 2) {toast.maketext (this, "point must be greater than 2", toast.length_short).show(); return; }Copy the code
  • And then I want to clear the lines
if (mPolyline! =null){ mPolyline.remove(); }Copy the code
  • Let’s start drawing polygons
/** * Private void drawPolygon() {if (polygon! = null) { polygon.remove(); } LatLng ll = null; List<LatLng> pts = new ArrayList<LatLng>(); for (int i = 0; i < ids.size(); i++) { String s = ids.get(i); Log.e("aaa", "key= " + s + " and value= " + latlngs.get(s).toString()); ll = latlngs.get(s); pts.add(ll); } OverlayOptions ooPolygon = new PolygonOptions().points(pts) .stroke(new Stroke(5, 0xAA00FF00)).fillColor(0xAAFFFF00); polygon = (Polygon) baidumap.addOverlay(ooPolygon); }Copy the code
  • Find the center point of the polygon and overlay the text information at this point
for (int i = 0; i < size; i++) {
    l = latlngs.get(ids.get(i));
    la = la + l.latitude;
    lo = lo + l.longitude;
}

Copy the code
AlertDialog.Builder builder = new AlertDialog.Builder(this); Builder.settitle (" Please enter a name: "); View inflate = View.inflate(this, R.layout.dialog_aliasname, null); final EditText edt_alias = inflate.findViewById(R.id.edt_alias); builder.setView(inflate); Builder. SetPositiveButton (" sure," new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { String trim = edt_alias.getText().toString().trim(); If (trim.equals("")) {toasts. MakeText (main2Activity. this, "Alias cannot be empty!" , Toast.LENGTH_SHORT).show(); return; } drawPolygon(); // Add text to the center of the polygon LatLng llText = new LatLng(la/size, lo/size); OverlayOptions ooText = new TextOptions() .fontSize(24).fontColor(0xFFFF00FF).text(trim + "") .position(llText); baidumap.addOverlay(ooText); polygonMap.put(trim, polygon); aliasname.add(trim); polygon = null; Log.e("aaa", "polygonmap.size ()"); Log.e("aaa", "aliasname.toString()"); for (int j = 0; j < markers.size(); j++) { markers.get(j).remove(); } //polygons.add(polygon); //polygon = null; latlngs.clear(); ids.clear(); }}); Builder. SetNegativeButton (" cancel ", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { } }); builder.create().show();Copy the code

Step 4: Determine if a point is in a polygon

In this case we need a class SpatialRelationUtil and in this class we have a method, isPolygonContainsPoint, which is very convenient to determine whether a point is in a polygon or not. The code is as follows:Copy the code
for (int i = 0; i < aliasname.size(); i++) { name = aliasname.get(i); Log.e("aaa", "check alias:" + name); polygon = polygonMap.get(name); String s = polygon.getPoints().toString(); Log.e("aaa", "sssss---->" + s); / / determine whether a point in the polygon polygonContainsPoint = SpatialRelationUtil. IsPolygonContainsPoint (polygon. GetPoints (), new LatLng(latitude, longitude)); If (polygonContainsPoint) {toast. makeText(this, "this point is in the" + name + "area. , Toast.LENGTH_SHORT).show(); areas.add(name); } } Log.e("aaa","areas"+areas.toString()); if (areas.size() > 0) { String message = areas.toString(); ShowDialog (" where: "+message); } else {showDialog(" This point is not in any region." ); }}Copy the code

ShowDialog (String mess) has the following code:

private void showDialog(String message) { AlertDialog.Builder builder = new AlertDialog.Builder(this); Builder.settitle (" Baidu map "); builder.setMessage(message); Builder. SetPositiveButton (" sure," new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { } }); builder.create().show(); }Copy the code
Well, that's pretty much itCopy the code

Finally, here is the demo:

Demo Download Address