标记移动时绘制折线映射v2

时间:2015-04-23 16:29:49

标签: android google-maps google-maps-api-2 polyline

我对Google Maps API v2的问题有疑问。

我的英语非常糟糕,我正在与Google的翻译工作,我希望您能理解我,我的问题是:是否可以实时更正Google Maps API v2中的折线点? ,我需要在带有可拖动标记的Google map v2混合中包围一个给定的边界,但是当我移动标记时,折线没有修正到它的新形状,有人可以告诉我我该怎么做吗?,这是我的片段代码

public class MapsActivity extends FragmentActivity implements GoogleMap.OnMapClickListener, GoogleMap.OnMapLongClickListener, GoogleMap.OnMarkerDragListener {

    //utilidad
    int cont;
    String description;
    ArrayList<LatLng> PolyLinePoints = new ArrayList<LatLng>();

    //elementos del mapa
    final int RQS_GooglePlayServices = 1;
    Location myLocation;
    boolean markerClicked;
    PolygonOptions polygonOptions;
    Polygon polygon;
    private GoogleMap mMap; // Might be null if Google Play services APK is not available.

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

    }

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

    /**
     * Sets up the map if it is possible to do so (i.e., the Google Play services APK is correctly
     * installed) and the map has not already been instantiated.. This will ensure that we only ever
     * call {@link #setUpMap()} once when {@link #mMap} is not null.
     * <p/>
     * If it isn't installed {@link SupportMapFragment} (and
     * {@link com.google.android.gms.maps.MapView MapView}) will show a prompt for the user to
     * install/update the Google Play services APK on their device.
     * <p/>
     * A user can return to this FragmentActivity after following the prompt and correctly
     * installing/updating/enabling the Google Play services. Since the FragmentActivity may not
     * have been completely destroyed during this process (it is likely that it would only be
     * stopped or paused), {@link #onCreate(Bundle)} may not be called again so we should call this
     * method in {@link #onResume()} to guarantee that it will be called.
     */
    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();

            mMap.setMyLocationEnabled(true);
            mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
            mMap.setOnMapClickListener(this);
            mMap.setOnMapLongClickListener(this);
            mMap.setOnMarkerDragListener(this);
            mMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
                @Override
                public void onInfoWindowClick(Marker marker) {
                    //marker.remove();

                }
            });
            // Check if we were successful in obtaining the map.
            if (mMap != null) {
                setUpMap();
            }
        }
    }

    /**
     * This is where we can add markers or lines, add listeners or move the camera. In this case, we
     * just add a marker near Africa.
     * <p/>
     * This should only be called once and when we are sure that {@link #mMap} is not null.
     */
    private void setUpMap() {
        mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Mi marcador").snippet("un marcador simple").draggable(false));
    }

    @Override
    public void onMapClick(LatLng point) {
        mMap.animateCamera(CameraUpdateFactory.newLatLng(point));

        markerClicked = false;
    }

    @Override
    public void onMapLongClick(LatLng point) {
        //mMap.addMarker(new MarkerOptions().position(point).title(String.valueOf(cont)).snippet("Clic aqui para eliminar").draggable(true));


        // Instantiating the class MarkerOptions to plot marker on the map
        MarkerOptions markerOptions = new MarkerOptions();

        // Setting latitude and longitude of the marker position
        markerOptions.position(point);

        // Setting titile of the infowindow of the marker
        markerOptions.title("Position");

        // Setting the content of the infowindow of the marker
        markerOptions.snippet(point.latitude + ", "+ point.longitude);

        //can move Marker on the all map
        markerOptions.draggable(true);

        // Instantiating the class PolylineOptions to plot polyline in the map
        PolylineOptions polylineOptions = new PolylineOptions();

        // Setting the color of the polyline
        polylineOptions.color(Color.RED);

        // Setting the width of the polyline
        polylineOptions.width(3);

        // Adding the taped point to the ArrayList
        PolyLinePoints.add(point);

        // Setting points of polyline
        polylineOptions.addAll(PolyLinePoints);

        // Adding the polyline to the map
        mMap.addPolyline(polylineOptions);

        // Adding the marker to the map
        mMap.addMarker(markerOptions);

        markerClicked = false;
    }

    @Override
    public void onMarkerDragStart(Marker marker) {

    }

    @Override
    public void onMarkerDrag(Marker marker) {

    }

    @Override
    public void onMarkerDragEnd(Marker marker) {

        //Point[] mark = mMap.getProjection().toScreenLocation(marker.getPosition());

        Toast.makeText(this, "LatLgn: " + mark.toString(), Toast.LENGTH_SHORT).show();
    }
}

这是我所做的图片,链接在这里(我无法添加图片发布):

enter image description here

这是我尝试更新标记位置时会发生什么的图片,链接在这里(我无法添加图片到帖子):

enter image description here

有人可以告诉我我需要什么吗?或者我可以找到解决方案的帖子?

非常感谢你的关注,希望你能帮忙

1 个答案:

答案 0 :(得分:0)

方法:

  1. 使用 fusedLocationProviderClient 获取当前位置更新。
  2. 现在创建一个 LatLng 列表并将更新的位置添加到该列表中。
  3. 现在从该列表创建多段线并将其添加到谷歌地图
  4. 每次我们在回调中获得一个新位置时,我们将执行 list.add(newLatLng) 然后删除旧折线并创建一条新折线并附加到地图。
/* This is a sample code from my application, but you need to set up it. It is not ready to use because we have different uses.*/


private GoogleMap map;
    private PlacesClient placesClient;
    private FusedLocationProviderClient fusedLocationProviderClient;
    private LocationRequest locationRequest;
    private LocationCallback locationCallback;
    private Location lastKnownLocation;
    private Location currentLocation;

private void drawPolyLineWhereWalked(ArrayList<LatLng> latLngArrayList) {
        PolylineOptions polyLineOptions = new PolylineOptions()
                .color(ContextCompat.getColor(getApplicationContext(),
                        R.color.colorPrimary))
                .width(16)
                .startCap(new ButtCap())
                .jointType(JointType.ROUND)
                .addAll(latLngArrayList);

        listPloyLine.add(map.addPolyline(polyLineOptions));
    }

private void updateCameraPosition(Location currentLocation, Location destLocation) {

        LatLng currentLatLng = new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude());
        if (lastKnownLocation == null) lastKnownLocation = currentLocation;

        // calculate bearing to find heading direction
        float bearingValue = lastKnownLocation.bearingTo(currentLocation);

        CameraPosition cameraPosition;
        if (currentLocation.distanceTo(lastKnownLocation) > 50)
            cameraPosition = new CameraPosition.Builder()
                    .target(currentLatLng).zoom(20).tilt(45f).bearing(bearingValue).build();
        else
            cameraPosition = new CameraPosition.Builder()
                    .target(currentLatLng).zoom(20).tilt(45f).build();

        if (isRecenter) map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));

        lastKnownLocation = currentLocation;

        // this list contain latLng to create a polyline
        if (al_LatLng == null) al_LatLng = new ArrayList<>();
        al_LatLng.add(currentLatLng);

        drawPolyLineWhereWalked(al_LatLng);

        // stopping if we have reached in a radius of 30m from destination
        if (currentLocation.distanceTo(destLocation) < 30) stopDriving();
    }

private void startLoopForCurrentLocation() {

        if (ActivityCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION) !=
                PackageManager.PERMISSION_GRANTED &&
                ActivityCompat.checkSelfPermission(this,
                        Manifest.permission.ACCESS_COARSE_LOCATION) !=
                        PackageManager.PERMISSION_GRANTED) {
            return;
        }

        fusedLocationProviderClient.requestLocationUpdates
                (locationRequest, locationCallback, null);
    }

 - List item