简体   繁体   English

Android Google Map + Pusher(实时)监听器

[英]Android Google Map + Pusher (real time) Listener

I have a fragment and I'm using getMapAsync method from Google Maps API, it is working correctly. 我有一个片段,正在使用Google Maps API中的getMapAsync方法,它工作正常。

At the same time, I want to connect my app to Pusher, and in every event I receive, I want to put a Marker in the map (I want to show every users locations in real time, when they connect to the app). 同时,我想将我的应用程序连接到Pusher,并且在收到的所有事件中,我都希望在地图上放置一个标记(我希望在用户连接到该应用程序时实时显示每个用户的位置)。

Everything is working how it supposed to, but I can't access the googleMap var inside the Pusher listener (onEvent method). 一切都按预期进行,但是我无法访问Pusher侦听器(onEvent方法)中的googleMap var。 Why?? 为什么??

I'm new to Java programming, and I think I'm doing something very wrong, :/ 我是Java编程的新手,我认为我做错了很多,:/

public class HomeFragment extends Fragment implements OnMapReadyCallback,PresenceChannelEventListener{

private me.agiliza.agilizame.models.User _user;
private View _view;
private MapView _map;
private GoogleMap _googleMap;
private Pusher _pusher;
private PresenceChannel _presenceChannel;
private boolean _isSubscribedToPresence;

public HomeFragment() {
    // Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    _view = inflater.inflate(R.layout.fragment_home, container, false);

    _user = UserManager.getInstance(getActivity().getApplicationContext());

    _map = (MapView) _view.findViewById(R.id.vMap);

    _map.onCreate(savedInstanceState);
    _map.onResume(); // needed to get the map to display immediately

    MapsInitializer.initialize(getActivity().getApplicationContext());

    _map.getMapAsync(this);

    return _view;
}

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

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

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

@Override
public void onLowMemory() {
    super.onLowMemory();
    _map.onLowMemory();
}


@Override
public void onMapReady(GoogleMap googleMap) {
    Log.i("Carregou", "Mapa");
    _googleMap = googleMap;
    _googleMap.setMyLocationEnabled(true);
    _googleMap.getUiSettings().setMyLocationButtonEnabled(false);

    loadConnectedProviders();

    _googleMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
        @Override
        public void onMyLocationChange(Location location) {
            if (_isSubscribedToPresence) {
                LatLng coordinates = new LatLng(location.getLatitude(), location.getLongitude());
                _googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(coordinates, 15));
                Log.d(Utils.TAG, "Atualizou localização");
                _googleMap.setMyLocationEnabled(false);
                _googleMap.addMarker(new MarkerOptions().position(coordinates)).setTitle("Minha localização");

                JSONObject jsonObject = new JSONObject();
                try {
                    jsonObject.put("id", _user.getId());
                    jsonObject.put("latitude", coordinates.latitude);
                    jsonObject.put("longitude", coordinates.longitude);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                _presenceChannel.trigger("client-locup", jsonObject.toString());
            }
        }
    });

}

public void loadConnectedProviders(){
    _pusher = PusherManager.getInstance(getActivity());
    _pusher.unsubscribe("presence-providers");
    _presenceChannel = _pusher.subscribePresence("presence-providers", this, "client-locup");

}

@Override
public void onUsersInformationReceived(String channelName, Set<User> users) {}

@Override
public void userSubscribed(String channelName, User user) {
}

@Override
public void userUnsubscribed(String channelName, User user) {}

@Override
public void onAuthenticationFailure(String message, Exception e) {
    _isSubscribedToPresence = false;
}

@Override
public void onSubscriptionSucceeded(String channelName) {
    _isSubscribedToPresence = true;
}

@Override
public void onEvent(String channelName, String eventName, String data) {
            try {
                JSONObject jsonObject = new JSONObject(data);
                int userId = jsonObject.getInt("id");
                LatLng latLng = new LatLng(jsonObject.getDouble("latitude"),jsonObject.getDouble("longitude"));

                // I cant get this to work
                //_googleMap.addMarker(new MarkerOptions().position(latLng));

                Log.d(Utils.TAG, "Id is " + userId + " Value of lat is " + latLng.latitude + " and long is " + latLng.longitude);
            } catch (JSONException e) {
                e.printStackTrace();
            }

}

} }

You must getting NullPointerException, because _googleMap can not be ready. 您必须获取NullPointerException,因为_googleMap无法准备好。 Try something like this. 尝试这样的事情。

private final Stack<JSONObject> mPending = new Stack<>();

@Override
public void onMapReady(GoogleMap googleMap) {
    Log.i("Carregou", "Mapa");
    _googleMap = googleMap;
    syncMarkers(); // <=== LOOK HERE
    _googleMap.setMyLocationEnabled(true);
    _googleMap.getUiSettings().setMyLocationButtonEnabled(false);

    loadConnectedProviders();

    _googleMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
        @Override
        public void onMyLocationChange(Location location) {
            if (_isSubscribedToPresence) {
                LatLng coordinates = new LatLng(location.getLatitude(), location.getLongitude());
                _googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(coordinates, 15));
                Log.d(Utils.TAG, "Atualizou localização");
                _googleMap.setMyLocationEnabled(false);
                _googleMap.addMarker(new MarkerOptions().position(coordinates)).setTitle("Minha localização");

                JSONObject jsonObject = new JSONObject();
                try {
                    jsonObject.put("id", _user.getId());
                    jsonObject.put("latitude", coordinates.latitude);
                    jsonObject.put("longitude", coordinates.longitude);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                _presenceChannel.trigger("client-locup", jsonObject.toString());
            }
        }
    });

}

    @Override
    public void onEvent(String channelName, String eventName, String data) {
        try {
            JSONObject jsonObject = new JSONObject(data);
            mPending.add(jsonObject);
            syncMarkers(); // <=== LOOK HERE
            Log.d(Utils.TAG, "Id is " + userId + " Value of lat is " + latLng.latitude + " and long is " + latLng.longitude);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void syncMarkers() {
        if (_googleMap != null) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    while (!mPending.empty()) {
                        JSONObject jsonObject = mPending.pop();
                        int userId = jsonObject.getInt("id");
                        LatLng latLng = new LatLng(jsonObject.getDouble("latitude"), jsonObject.getDouble("longitude"));
                        _googleMap.addMarker(new MarkerOptions().position(latLng));
                    }
                }
            });
        }
    }

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM