如何刷新地图上的标记?

时间:2017-06-28 11:14:47

标签: android google-maps

我在地图上只有2个标记

1-我想尽可能用最大缩放显示标记

2-我希望在此之后用计时器刷新标记位置。

我想使用凌空从服务器加载A和B的信息。我是Beginer

这是我的代码:

import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class Test extends FragmentActivity implements OnMapReadyCallback {
    RequestQueue requestQueue;
    String b_lat, b_lon, a_lat, a_lon;

    private GoogleMap mMap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);


    }



    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        LatLng a_local = new LatLng(Double.parseDouble(a_lat), Double.parseDouble(a_lon));
        LatLng b_local = new LatLng(Double.parseDouble(b_lat), Double.parseDouble(b_lon));

        mMap.addMarker(new MarkerOptions().position(a_local).title("a") 
                .snippet("xxx")
                .icon(BitmapDescriptorFactory.fromResource(R.drawable.marker_a))).showInfoWindow();

        mMap.addMarker(new MarkerOptions().position(b_local).title("b")
                .snippet("yyy")
                .icon(BitmapDescriptorFactory.fromResource(R.drawable.marker_b))).showInfoWindow();


        mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
        mMap.getUiSettings().setZoomControlsEnabled(true);
        mMap.getUiSettings().setCompassEnabled(true);
        mMap.getUiSettings().setAllGesturesEnabled(true); 
        mMap.getUiSettings().setMyLocationButtonEnabled(true);
        if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

            return;
        }
        mMap.setMyLocationEnabled(true);





        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(a_local,16));

        mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {
                Toast.makeText(Test.this,latLng.latitude + ", " +latLng.longitude, Toast.LENGTH_SHORT).show();

            }
        });
    }
    public void a_b_locations(){
        try {
            SharedPreferences myshared = getSharedPreferences("file", Context.MODE_PRIVATE);
            a_lat= myshared.getString("a_lat",""); 
            a_lon= myshared.getString("a_lon","") ; 
            b_lat= myshared.getString("b_lat","") ;
            b_lon= myshared.getString("b_lon","") ;


        }
        catch(Exception e) {
            return ;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        a_b_locations();

    }

    public void load_locations_from_server() {

        String URL="http://myweb.com";

        requestQueue = Volley.newRequestQueue(this);
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, URL,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {

                        try {
                            JSONArray jsonArray = response.getJSONArray("locations");

                            for (int i = 0; i < jsonArray.length(); i++) {
                                JSONObject respons = jsonArray.getJSONObject(i);

                                a_lat=respons.getString("a_lat");
                                a_lon=respons.getString("a_lon");
                                b_lat=respons.getString("b_lat");
                                b_lon=respons.getString("b_lon");                                

                            }

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

                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e("VOLLEY", "ERROR");
            }
        }

        );
        requestQueue.add(jsonObjectRequest);

    }
}

2 个答案:

答案 0 :(得分:1)

您需要在映射就绪后调用load_locations_from_server()方法,这是onMapReady()方法。

https://developers.google.com/maps/documentation/android-api/start

了解详情

要设置标记的新位置,您只需使用:

Marker.setPosition(LatLng latlng);

所以你需要为标记创建两个变量。

私人标记mMarkerA; 私人标记mMarkerB;

然后在你的onMapReady()中初始化它们:

@Override
public void onMapReady(GoogleMap googleMap) {
  mMap = googleMap;

  ...

  mMarkerA = mMap.addMarker(new MarkerOptions().position(a_local).title("a") 
            .snippet("xxx")
            .icon(BitmapDescriptorFactory.fromResource(R.drawable.marker_yellow))).showInfoWindow();

  mMarkerB = mMap.addMarker(new MarkerOptions().position(b_local).title("b")
            .snippet("yyy")
            .icon(BitmapDescriptorFactory.fromResource(R.drawable.markerb))).showInfoWindow();
  ...
}

然后,当您从服务器获取位置时,可以刷新它们:

a_lat=respons.getString("a_lat");
a_lon=respons.getString("a_lon");
b_lat=respons.getString("b_lat");
b_lon=respons.getString("b_lon");

// refresh marker
mMarkerA.setPosition(new LatLng(a_lat, a_lon));
mMarkerA.setPosition(new LatLng(b_lat, b_lon));

显示两个标记

要使用额外填充显示两个标记,您可以像以下方法一样使用LatLngBounds

private void zoomToShowBothPoints(LatLng firstLatLng, LatLng secondLatLng) {
    LatLngBounds bounds =
        new LatLngBounds.Builder().include(firstLatLng).include(secondLatLng).build();

    Point displaySize = new Point();
    getWindowManager().getDefaultDisplay().getSize(displaySize);
    mMap.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds, displaySize.x - 20, displaySize.y - 20, 50));
  }

答案 1 :(得分:0)

尝试将标记存储在变量上:

private Marker A;
private Marker B;
  A = mMap.addMarker(new MarkerOptions().position(a_local).title("a") 
            .snippet("xxx")
            .icon(BitmapDescriptorFactory.fromResource(R.drawable.marker_yellow))).showInfoWindow();

   B = mMap.addMarker(new MarkerOptions().position(b_local).title("b")
            .snippet("yyy")
            .icon(BitmapDescriptorFactory.fromResource(R.drawable.markerb)))

然后创建一个定时器,它将调用你的load_locations_from_server()方法并刷新标记并在响应回调函数中更新相机:

                public void onResponse(JSONObject response) {

                    try {
                        JSONArray jsonArray = response.getJSONArray("locations");

                        for (int i = 0; i < jsonArray.length(); i++) {
                            JSONObject respons = jsonArray.getJSONObject(i);

                            a_lat=respons.getString("a_lat");
                            a_lon=respons.getString("a_lon");
                            b_lat=respons.getString("b_lat");
                            b_lon=respons.getString("b_lon");        

                            A.setLocation(LatLng(a_lat,a_lon));
                            B.setLocation(LatLng(b_lat,b_lon));

                            LatLngBounds.Builder builder = new LatLngBounds.Builder();
                            builder.include(A.getPosition());
                            builder.include(B.getPosition());
                            LatLngBounds bounds = builder.build();
                            CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, 0);
                            mMap..moveCamera(cu);
                        }

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