简体   繁体   English

当网络服务中的经度和纬度发生变化时,如何在Google地图中移动标记?

[英]How to move the marker in Google map when the latitude and longitude changes in webservices?

In my application am plotting a set of latitude and longitude from web services to Google map but when the Latitude and longitude changes in the web services the marker is not moving. 在我的应用程序中,正在绘制一组从Web服务到Google地图的经度和纬度,但是当Web服务中的经度和纬度发生变化时,标记不会移动。 when I close and open the application it updates the changes, but I need to move the marker without closing and restarting the application. 当我关闭并打开应用程序时,它会更新更改,但是我需要移动标记而无需关闭并重新启动应用程序。 My Updated code is given below . 我的更新代码如下。

 public View onCreateView(LayoutInflater inflater, ViewGroup container, 
            Bundle savedInstanceState) { 
        rootView = inflater.inflate(R.layout.fragment_layout_one, container, false); 


        MapsInitializer.initialize(getActivity()); 

        mMapView = (MapView)rootView.findViewById(R.id.mapView); 
        mMapView.onCreate(mBundle); 


        MapsInitializer.initialize(getActivity()); 

        if (android.os.Build.VERSION.SDK_INT > 9) { 
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder() 
            .permitAll().build(); 
            StrictMode.setThreadPolicy(policy); 
        } 

        /* new DownloadJSON().execute(); 
        setUpMapIfNeeded(rootView); */
        /*
        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                 new DownloadJSON().execute(); 
                    setUpMapIfNeeded(rootView); 

                 Toast.makeText(getActivity(), "Data Updated!!!! ", Toast.LENGTH_SHORT).show();
                 Log.d("Data in Log", "");
            }
        }, 10*1000);*/

        new DownloadJSON().execute(); 
        setUpMapIfNeeded(rootView);

        LocationManager locman = (LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE);
        //locman.requestLocationUpdates(minTime, minDistance, criteria, intent);
        locman.requestLocationUpdates(LocationManager.GPS_PROVIDER, 000, 10, this);



        return rootView; 
    } 

    private void setUpMapIfNeeded(View inflatedView) { 
        if (mMap == null) { 
            mMap = ((MapView) inflatedView.findViewById(R.id.mapView)).getMap(); 
            mMap.setMyLocationEnabled(true); 

            Location myLocation = mMap.getMyLocation(); 
            if (mMap != null) {  
                // setUpMap(); 
                mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() { 

                    @Override 
                    public void onMyLocationChange(Location arg0) { 

                        // TODO Auto-generated method stub 

                        final LatLngBounds.Builder builder = new LatLngBounds.Builder(); 
                        for (int i = 0; i < arraylist1.size(); i++) { 
                            final LatLng position = new LatLng(Double 
                                    .parseDouble(arraylist1.get(i).get("Latitude")), 
                                    Double.parseDouble(arraylist1.get(i).get( 
                                            "Longitude"))); 
                            String ime1 = arraylist1.get(i).get("IME");
                            final MarkerOptions options = new MarkerOptions() 
                            .position(position); 

                            mMap.addMarker(options); 
                            mMap.addMarker(options.icon(BitmapDescriptorFactory .fromResource(R.drawable.buspng)).title(ime1));
                            //options.title(ime1);
                            builder.include(position); 
                        } 
                        LatLng latLng = new LatLng(arg0.getLatitude(), arg0 
                                .getLongitude()); 

                        mMap.setMyLocationEnabled(true); 

                        mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng)); 
                        // mMap.setOnMapClickListener(null); 
                        mMap.setOnMarkerClickListener(null); 

                        mMap.animateCamera(CameraUpdateFactory.zoomTo(9)); 
                    } 
                }); 

            } 
        } 
    } 

    /*  protected void retrieveAndAddCities() throws IOException { 
        HttpURLConnection conn = null; 
        final StringBuilder json = new StringBuilder(); 
        try { 

            URL url = new URL(SERVICE_URL); 
            conn = (HttpURLConnection) url.openConnection(); 
            InputStreamReader in = new InputStreamReader(conn.getInputStream()); 

            int read; 
            char[] buff = new char[1024]; 
            while ((read = in.read(buff)) != -1) { 
                json.append(buff, 0, read); 
            } 
        } catch (IOException e) { 
            Log.e(LOG_TAG, "Error connecting to service", e); 
            throw new IOException("Error connecting to service", e); 
        } finally { 
            if (conn != null) { 
                conn.disconnect(); 
            } 
        } 
        new DownloadJSON().execute(); 

    } */

    private class DownloadJSON extends AsyncTask<Void, Void, Void> { 
        String result=""; 
        @Override 
        protected void onPreExecute() { 
            super.onPreExecute(); 
        }

        @Override 
        protected Void doInBackground(Void... params) { 
            try { 
                arraylist1 = new ArrayList<HashMap<String, String>>(); 

                JSONParser jParser = new JSONParser(); 
                String result = ""; 

                json = jParser.getJSONFromUrl(SERVICE_URL); 

                try { 
                    arraylist1.clear(); 

                    jsonarray = json.getJSONArray("SingleIMEs"); 
                    Log.d("Haaaaaaaaaaaa", "" + json); 

                    for (int i = 0; i < jsonarray.length(); i++) { 
                        Log.d("H11111111111111111111111111", 
                                "" + jsonarray.length()); 
                        map = new HashMap<String, String>(); 
                        json = jsonarray.getJSONObject(i); 

                        // pubname = json.getString("PubName"); 
                        latitude = json.getDouble("Latitude"); 
                        longitude = json.getDouble("Longitude"); 
                        ime = json.getString("IME");
                        //  map.put("PubName", json.getString("PubName")); 
                        //map.put("PubID", json.getString("PubID")); 
                        map.put("Latitude", json.getString("Latitude")); 
                        map.put("Longitude", json.getString("Longitude")); 
                        map.put("IME", json.getString("IME"));
                        arraylist1.add(map); 
                    } 

                } catch (JSONException e) { 
                    Log.e("log_tag", "Error parsing data " + e.toString()); 
                    result="Error"; 
                    e.printStackTrace(); 
                } 
            }catch(Exception e){ 
                result="Error"; 
            } 

            return null; 
        } 

        protected void onPostExecute(Void args) { 

            // mProgressDialog.dismiss(); 

        } 
    } 

    @Override 
    public void onResume() { 
        super.onResume(); 
        mMapView.onResume(); 
    } 

    @Override 
    public void onPause() { 
        super.onPause(); 
        mMapView.onPause(); 
    } 

    @Override 
    public void onDestroy() { 
        mMapView.onDestroy(); 
        super.onDestroy(); 
    }

    @Override
    public void onLocationChanged(Location location) {
        // TODO Auto-generated method stub

        Toast.makeText(getActivity(), "onLocationUpdated!!!", Toast.LENGTH_SHORT).show();
        Log.d("onLocationUpdated!!!","");
        new DownloadJSON().execute(); 
        setUpMapIfNeeded(rootView);

    }

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

    }

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

    }

    @Override
    public void onProviderDisabled(String provider) {

        // TODO Auto-generated method stub

    } 

}

You can use handler for updating the location.Inside run() just call that webservice.And just put the marker in current location. 您可以使用处理程序来更新位置。在run()内部只需调用该Web服务,然后将标记放在当前位置即可。

// Call current location API after 3 Min
    handler.postDelayed(run, 3000 * 60);

    Runnable run = new Runnable() {
            @Override
            public void run() {
                if (isConnected(context)) {
                    new CurrentPosTask().execute();
                } else {
                    Toast.makeText(context, "No internet connection",
                            Toast.LENGTH_LONG).show();
                }

            }
        };

Don't forget call below method into onDestroy() method 不要忘记将下面的方法调用到onDestroy()方法中

 // Stop the handler
        handler.removeCallbacks(run);

Hope it will help you. 希望对您有帮助。 Let me know once done. 完成后让我知道。

You have to set repeat alarm to check the web service at intervel 您必须设置重复警报才能在intervel检查Web服务

private AlarmManager alarmMgr;
private PendingIntent alarmIntent;

alarmMgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, AlarmReceiver.class);
alarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0);

alarmMgr.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
    SystemClock.elapsedRealtime() +
    60 * 1000, alarmIntent);

 // Set the alarm to start at approximately 2:00 p.m.
 Calendar calendar = Calendar.getInstance();
 calendar.setTimeInMillis(System.currentTimeMillis());
 calendar.set(Calendar.HOUR_OF_DAY, 14);

// With setInexactRepeating(), you have to use one of the AlarmManager     interval
// constants--in this case, AlarmManager.INTERVAL_DAY.
alarmMgr.setInexactRepeating(AlarmManager.RTC_WAKEUP,   calendar.getTimeInMillis(),
    5000, alarmIntent);

and in alarm reciever class call web service and update the map position 并在警报接收器类别中调用Web服务并更新地图位置

public class AlarmReceiverextends WakefulBroadcastReceiver {
    new DownloadJSON().execute(); 
    setUpMapIfNeeded(rootView);
}

for full tutorial look developers.android https://developer.android.com/training/scheduling/alarms.html 有关完整的教程,请查看developer.android https://developer.android.com/training/scheduling/alarms.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在Google Map v2中获取标记的经度和纬度值 - How to get the longitude and latitude value of the marker in google map v2 当我从短信中接收经度和纬度时,如何在Google地图中添加标记 - How to add marker in google map when i recieve longitude and latitude from sms 如何从我在地图上设置的标记保存经度和纬度 - How to save longitude and latitude from the marker i set on the map 如何使用MSExcel中的纬度和经度对在Google地图上移动标记并每10秒刷新一次 - How can I move a marker on Google Maps using latitude & longitude pair from MSExcel and refresh every 10 seconds 转换谷歌地图中的纬度和经度? - converting latitude and longitude in google map? 我想通过从json获取经度和纬度在Google地图上显示标记 - i want to show marker on google map by getting longitude and latitude from json 如何测试纬度/经度点是否在地图内(不是谷歌地图) - How to test if a Latitude/Longitude point is within a Map (not google maps) 如何从谷歌地图 URL 获取纬度经度 - How to get latitude longitude from google map URL 如何通过纬度和经度在谷歌地图上显示多个位置? - how to display multiple location on google map by their latitude and longitude? 如何在android studio中的谷歌地图上获取选定位置的纬度和经度 - How to get latitude and longitude of select location on google map in android studio
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM