【问题标题】:move marker on google maps api 2在谷歌地图 api 2 上移动标记
【发布时间】:2013-04-25 03:10:53
【问题描述】:

如何在 Google maps api V2 上移动标记?我正在使用下面的代码,但它不会在地图上移动标记。我在这里做错了什么?这应该在位置更改时起作用,因此我添加了 onLocationChanged 方法,并且正在获取位置详细信息并尝试在新细节上移动标记,但这不起作用。

这是我的代码:

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;

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 com.google.gson.Gson;

public class MapViewActivity extends Activity implements LocationListener,
        SensorEventListener, OnClickListener {

    GoogleMap googleMap;

    private boolean started = false;
    private ArrayList<AccelLocData> sensorData;
    private SensorManager sensorManager;
    private Button btnStart, btnStop;
    private String provider;

    // File root, dir, sensorFile;
    FileOutputStream fOut;
    private Sensor mAccelerometer;
    private FileWriter writer;
    private DatabaseHelper databaseHelper;
    private BroadcastReceiver alarmReceiver;
    private PendingIntent pendingIntentSender, pendingIntentReceiver;

    private AlarmManager alarmManager;
    private Intent alarmIntent,alarmIntent2;

    // private Button btnUpload;

    @SuppressLint("NewApi")
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        try {

            databaseHelper = new DatabaseHelper(this);
            databaseHelper.removeAll();


            Log.v("datacount",
                    Integer.toString(databaseHelper.getLocDataCount()));

            sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
            mAccelerometer = sensorManager
                    .getDefaultSensor(Sensor.TYPE_ACCELEROMETER);

            btnStart = (Button) findViewById(R.id.btnStart);
            btnStop = (Button) findViewById(R.id.btnStop);
            btnStart.setOnClickListener(this);
            btnStop.setOnClickListener(this);
            btnStart.setEnabled(true);
            btnStop.setEnabled(false);

            alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);

            int status = GooglePlayServicesUtil
                    .isGooglePlayServicesAvailable(getBaseContext());
            if (status != ConnectionResult.SUCCESS) { // Google Play Services
                                                        // are
                                                        // not available

                int requestCode = 10;
                Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status,
                        this, requestCode);
                dialog.show();

            } else { // Google Play Services are available

                // Getting reference to the SupportMapFragment of
                // activity_main.xml
                // SupportMapFragment supportMapFragment = (MapFragment)
                // getFragmentManager().findFragmentById(R.id.map);

                // Getting GoogleMap object from the fragment
                googleMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();


                // can use for overlay on the map
                List<Double> latList = new ArrayList<Double>();
                latList.add(145.7309593);
                latList.add(146.34);
                latList.add(147.34);

                List<Double> lonList = new ArrayList<Double>();
                lonList.add(-122.6365384);
                lonList.add(-123.6365384);
                lonList.add(-124.6365384);

                for (int i = 0; i < 3; i++) {
                    // LatLng latLng = new LatLng(45.7309593, -122.6365384);
                    LatLng latLng = new LatLng(latList.get(i).doubleValue(),
                            lonList.get(i).doubleValue());
                    googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
                    googleMap
                            .addMarker(new MarkerOptions()
                                    .position(latLng)
                                    .title("My Spot")
                                    .snippet("This is my spot!")
                                    .icon(BitmapDescriptorFactory
                                            .defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
                }

                // Enabling MyLocation Layer of Google Map
                googleMap.setMyLocationEnabled(true);

                LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

                Criteria criteria = new Criteria();
                provider = locationManager.getBestProvider(criteria, true);
                Location location = locationManager
                        .getLastKnownLocation(provider);

                if (location != null) {
                    onLocationChanged(location);
                }

                locationManager
                        .requestLocationUpdates(provider, 20000, 0, this);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public void onSensorChanged(SensorEvent event) {

        if (started) {

            double x = event.values[0];
            double y = event.values[1];
            double z = event.values[2];

            long timestamp = System.currentTimeMillis();

            LocationManager locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
            Criteria criteria = new Criteria();
            criteria.setPowerRequirement(Criteria.POWER_MEDIUM);
            criteria.setAccuracy(Criteria.ACCURACY_FINE);

            provider = locManager.getBestProvider(criteria, true);
            Location location = locManager.getLastKnownLocation(provider);

            double latitude = 0;
            double longitude = 0;
            if (location != null) {
                latitude = location.getLatitude();
                longitude = location.getLongitude();
            }
            AccelLocData accelLocData = new AccelLocData(timestamp, x, y, z,
                    latitude, longitude);

            // Log.d("X data","data x:" + data.getX());

            try {
                // writer.write(data.toString());
                 if (databaseHelper != null)
                 databaseHelper.insertLocData(accelLocData);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
    }

    @Override
    public void onLocationChanged(Location location) {

        TextView tvLocation = (TextView) findViewById(R.id.tv_location);

        // Getting latitude of the current location
        double latitude = location.getLatitude();

        // Getting longitude of the current location
        double longitude = location.getLongitude();

        // Creating a LatLng object for the current location
        LatLng latLng = new LatLng(latitude, longitude);

        // Showing the current location in Google Map
        googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));

        // Zoom in the Google Map
        googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));






    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.btnStart:

            Context context = getApplicationContext();
            alarmIntent = new Intent(context, AccelLocSender.class);

            AlarmManager alarmManager = (AlarmManager) context
                    .getSystemService(Context.ALARM_SERVICE);
            pendingIntentSender = PendingIntent.getBroadcast(context, 0,
                    alarmIntent, 0);

            alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
                    System.currentTimeMillis(), 60000, pendingIntentSender);

            alarmIntent2 = new Intent(context, AccelLocReceiver.class);
            pendingIntentReceiver = PendingIntent.getBroadcast(context, 0,
                    alarmIntent2, 0);
            alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
                    System.currentTimeMillis(), 30000, pendingIntentReceiver);

            btnStart.setEnabled(false);
            btnStop.setEnabled(true);
            Log.d("startbutton", "cam on click of start");
            started = true;

            // delete all files..
            // start thread to send data

            sensorManager.registerListener(this, mAccelerometer,
                    SensorManager.SENSOR_DELAY_FASTEST);
            break;
        case R.id.btnStop:
            try {
                btnStart.setEnabled(true);
                btnStop.setEnabled(false);
                // btnUpload.setEnabled(true);
                started = false;

                sensorManager.unregisterListener(this);

                Context context1 = getApplicationContext();
                AlarmManager alarmManager1 = (AlarmManager) context1
                        .getSystemService(Context.ALARM_SERVICE);
                alarmManager1.cancel(pendingIntentSender);
                alarmManager1.cancel(pendingIntentReceiver);

            //  System.exit(0);

                } catch (Exception e) {
                e.printStackTrace();
            }
            break;
        default:
            break;
        }

    }

    protected void onPause() {
        super.onPause();

        /*
         * if (writer != null) { try { writer.close(); } catch (IOException e) {
         * // TODO Auto-generated catch block e.printStackTrace(); } }
         */
    }

    protected void onResume() {
        super.onResume();
        /*
         * try { Log.d("onresume","called onresume"); writer = new
         * FileWriter(sensorFile, true); } catch (IOException e) { // TODO
         * Auto-generated catch block e.printStackTrace(); }
         */
    }

    @Override
    public void onProviderDisabled(String arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onProviderEnabled(String provider) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onAccuracyChanged(Sensor arg0, int arg1) {
        // TODO Auto-generated method stub

    }

}

【问题讨论】:

    标签: android google-maps google-maps-markers move marker


    【解决方案1】:

    addMarker 返回对标记的引用,以后可以更新该标记

    mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
                @Override
                public void onMapClick(LatLng latLng) {
                    if(mMarker == null) {
                        mMarker = mMap.addMarker(new MarkerOptions().position(latLng));
                    } else {
                        mMarker.setPosition(latLng);
                    }
                }
            });
    

    【讨论】:

    • 我做了几乎一样的事,但还是不动,你能看看我的question吗?
    • 谢谢老兄! @faisal1208 只需在每次验证时加上mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(myCurrentLocation, 20));
    【解决方案2】:

    移动标记的优化方式:

    标记 mMarker;

    在地图上添加标记后。在更改位置时您只需要设置位置而不是删除标记并重新添加。

    mMarker.setPosition(new LatLon(latLng));

    这将减少代码从删除和添加标记到直接设置位置并降低复杂性。 :)

    享受吧。

    【讨论】:

    • 我已经做了完全一样的,但它仍然不动,你能看看我的question吗?
    【解决方案3】:

    变量

     Marker now;
    

    在这部分添加标记和删除标记,当然把剩下的标记属性放进去:

     @Override
    public void onLocationChanged(Location location) {
    
        if(now != null){
                    now.remove();
    
                }
    
        TextView tvLocation = (TextView) findViewById(R.id.tv_location);
    
        // Getting latitude of the current location
        double latitude = location.getLatitude();
    
        // Getting longitude of the current location
        double longitude = location.getLongitude();
    
        // Creating a LatLng object for the current location
        LatLng latLng = new LatLng(latitude, longitude);
        now = googleMap.addMarker(new MarkerOptions().position(latLng)));
        // Showing the current location in Google Map
        googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
    
        // Zoom in the Google Map
        googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
    
    }
    

    【讨论】:

    • 嗨@JRowan,我不知道我的问题是否正确。但我说的是每当我在路上移动我的汽车时在地图上移动一个标记。一个例子可能是像谷歌导航器应用程序(不是在谈论寻找路线),只要你的汽车在路上移动,标记就会移动。你说的是同一个吗?
    • 嗨伙计们(@JRowan 和@MJ,我刚刚再次测试了我的应用程序。添加后我也遇到了问题。所以,我正在做一些后台处理(使用警报管理器来做)其他比在地图上移动标记。所以,如果该后台进程正在运行,那么标记很少在地图上移动。有人可以帮我解决这个问题吗?
    • 也许你应该为此做一个服务,然后按钮可以启动和停止服务
    • 你将更新设置为 20000 毫秒,如果这也是你所说的,那就太慢了
    • @JRowan 而不是删除和读取标记,您可以使用 Marker.setPoisition(LatLng)
    【解决方案4】:

    使用,使标记可拖动,

      MarkerOptions markerOptions = new MarkerOptions().position(myLaLn).title(
                "Current Location").draggable(true);
        map.addMarker(markerOptions);
    

    &获取拖拽位置&详情如下,

    map.setOnMarkerDragListener(new GoogleMap.OnMarkerDragListener() {
    
            @Override
            public void onMarkerDragStart(Marker marker) {
            }
    
            @Override
            public void onMarkerDragEnd(Marker marker) {
                Log.d(TAG, "latitude : "+ marker.getPosition().latitude);
                marker.setSnippet(marker.getPosition().latitude);
                map.animateCamera(CameraUpdateFactory.newLatLng(marker.getPosition()));
    
            }
    
            @Override
            public void onMarkerDrag(Marker marker) {
            }
    
        });
    

    【讨论】:

    • 没有名为setOnMarkerDragListener的内置方法
    • @faisal1208 有一个内置方法 setOnMarkerDragListener()
    【解决方案5】:

    您只是在位置更改时移动相机,您应该添加标记,然后它将在当前位置绘制标记。在添加标记之前,通过调用 googlmap.clear(); 清除所有以前的标记;

    【讨论】:

      猜你喜欢
      • 2017-09-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-08
      • 1970-01-01
      • 2013-04-08
      • 2020-05-07
      • 1970-01-01
      相关资源
      最近更新 更多