Search in sources :

Example 6 with LatLong

use of org.mapsforge.core.model.LatLong in project RSAndroidApp by RailwayStations.

the class MapsActivity method registerLocationManager.

public void registerLocationManager() {
    try {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            if (!askedForPermission) {
                ActivityCompat.requestPermissions(this, new String[] { android.Manifest.permission.ACCESS_FINE_LOCATION }, REQUEST_FINE_LOCATION);
                askedForPermission = true;
            }
            setMyLocSwitch(false);
            return;
        }
        locationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
        // getting GPS status
        final boolean isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        // if GPS Enabled get lat/long using GPS Services
        if (isGPSEnabled) {
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
            Log.d(TAG, "GPS Enabled");
            if (locationManager != null) {
                final Location loc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                myPos = new LatLong(loc.getLatitude(), loc.getLongitude());
            }
        } else {
            // getting network status
            final boolean isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
            // First get location from Network Provider
            if (isNetworkEnabled) {
                locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                Log.d(TAG, "Network Location enabled");
                if (locationManager != null) {
                    final Location loc = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                    myPos = new LatLong(loc.getLatitude(), loc.getLongitude());
                }
            }
        }
        setMyLocSwitch(true);
    } catch (final Exception e) {
        Log.e(TAG, "Error registering LocationManager", e);
        final Bundle b = new Bundle();
        b.putString("error", "Error registering LocationManager: " + e);
        locationManager = null;
        myPos = null;
        setMyLocSwitch(false);
        return;
    }
    Log.i(TAG, "LocationManager registered");
    updatePosition();
}
Also used : Bundle(android.os.Bundle) LatLong(org.mapsforge.core.model.LatLong) FileNotFoundException(java.io.FileNotFoundException) Location(android.location.Location)

Example 7 with LatLong

use of org.mapsforge.core.model.LatLong in project RSAndroidApp by RailwayStations.

the class Cluster method addItem.

/**
 * add item to cluster object
 *
 * @param item GeoItem object to be added.
 */
public synchronized void addItem(final T item) {
    synchronized (items) {
        items.add(item);
    }
    if (center == null) {
        center = item.getLatLong();
    } else {
        // computing the centroid
        double lat = 0, lon = 0;
        int n = 0;
        synchronized (items) {
            for (final T object : items) {
                if (object == null) {
                    throw new NullPointerException("object == null");
                }
                if (object.getLatLong() == null) {
                    throw new NullPointerException("object.getLatLong() == null");
                }
                lat += object.getLatLong().latitude;
                lon += object.getLatLong().longitude;
                n++;
            }
        }
        center = new LatLong(lat / n, lon / n);
    }
}
Also used : LatLong(org.mapsforge.core.model.LatLong)

Example 8 with LatLong

use of org.mapsforge.core.model.LatLong in project satstat by mvglasow.

the class MapSectionFragment method onLocationProvidersChanged.

/**
 * Updates internal data structures when the user's selection of location providers has changed.
 * @param providers The new set of location providers
 */
public void onLocationProvidersChanged(Set<String> providers) {
    Context context = this.getContext();
    List<String> allProviders = mainActivity.locationManager.getAllProviders();
    ArrayList<String> removedProviders = new ArrayList<String>();
    for (String pr : providerLocations.keySet()) if (!providers.contains(pr))
        removedProviders.add(pr);
    // remove cached locations and invalidators for providers which are no longer selected
    for (String pr : removedProviders) {
        providerLocations.remove(pr);
        providerInvalidators.remove(pr);
    }
    // ensure there is a cached location for each chosen provider (can be null)
    for (String pr : providers) {
        if ((allProviders.indexOf(pr) >= 0) && !providerLocations.containsKey(pr)) {
            Location location = new Location("");
            providerLocations.put(pr, location);
        }
    }
    // add overlays
    updateLocationProviderStyles();
    mapCircles = new HashMap<String, Circle>();
    mapMarkers = new HashMap<String, Marker>();
    Log.d(TAG, "Provider location cache: " + providerLocations.keySet().toString());
    Layers layers = mapMap.getLayerManager().getLayers();
    // remove all layers other than tile render layer from map
    for (Layer layer : layers) if (!(layer instanceof TileRendererLayer) && !(layer instanceof TileDownloadLayer)) {
        layer.onDestroy();
        layers.remove(layer);
    }
    for (String pr : providers) {
        // no invalidator for GPS, which is invalidated through GPS status
        if ((!pr.equals(LocationManager.GPS_PROVIDER)) && (providerInvalidators.get(pr)) == null) {
            final String provider = pr;
            final Context ctx = context;
            providerInvalidators.put(pr, new Runnable() {

                private String mProvider = provider;

                @Override
                public void run() {
                    Location location = providerLocations.get(mProvider);
                    if (location != null)
                        markLocationAsStale(location);
                    applyLocationProviderStyle(ctx, mProvider, Const.LOCATION_PROVIDER_GRAY);
                }
            });
        }
        String styleName = assignLocationProviderStyle(pr);
        LatLong latLong;
        float acc;
        boolean visible;
        if ((providerLocations.get(pr) != null) && (providerLocations.get(pr).getProvider() != "")) {
            latLong = new LatLong(providerLocations.get(pr).getLatitude(), providerLocations.get(pr).getLongitude());
            if (providerLocations.get(pr).hasAccuracy())
                acc = providerLocations.get(pr).getAccuracy();
            else
                acc = 0;
            visible = true;
            if (isLocationStale(providerLocations.get(pr)))
                styleName = Const.LOCATION_PROVIDER_GRAY;
            Log.d("MainActivity", pr + " has " + latLong.toString());
        } else {
            latLong = new LatLong(0, 0);
            acc = 0;
            visible = false;
            Log.d("MainActivity", pr + " has no location, hiding");
        }
        // Circle layer
        Resources res = context.getResources();
        TypedArray style = res.obtainTypedArray(res.getIdentifier(styleName, "array", context.getPackageName()));
        Paint fill = AndroidGraphicFactory.INSTANCE.createPaint();
        float density = context.getResources().getDisplayMetrics().density;
        fill.setColor(style.getColor(Const.STYLE_FILL, R.color.circle_gray_fill));
        fill.setStyle(Style.FILL);
        Paint stroke = AndroidGraphicFactory.INSTANCE.createPaint();
        stroke.setColor(style.getColor(Const.STYLE_STROKE, R.color.circle_gray_stroke));
        stroke.setStrokeWidth(Math.max(1.5f * density, 1));
        stroke.setStyle(Style.STROKE);
        Circle circle = new Circle(latLong, acc, fill, stroke);
        mapCircles.put(pr, circle);
        layers.add(circle);
        circle.setVisible(visible);
        // Marker layer
        Drawable drawable = style.getDrawable(Const.STYLE_MARKER);
        Bitmap bitmap = AndroidGraphicFactory.convertToBitmap(drawable);
        Marker marker = new Marker(latLong, bitmap, 0, -bitmap.getHeight() * 10 / 24);
        mapMarkers.put(pr, marker);
        layers.add(marker);
        marker.setVisible(visible);
        style.recycle();
    }
    // move layers into view
    updateMap();
}
Also used : Context(android.content.Context) Circle(org.mapsforge.map.layer.overlay.Circle) TileRendererLayer(org.mapsforge.map.layer.renderer.TileRendererLayer) ArrayList(java.util.ArrayList) TileDownloadLayer(org.mapsforge.map.layer.download.TileDownloadLayer) Drawable(android.graphics.drawable.Drawable) Marker(org.mapsforge.map.layer.overlay.Marker) Paint(org.mapsforge.core.graphics.Paint) TileRendererLayer(org.mapsforge.map.layer.renderer.TileRendererLayer) Layer(org.mapsforge.map.layer.Layer) TileDownloadLayer(org.mapsforge.map.layer.download.TileDownloadLayer) Bitmap(org.mapsforge.core.graphics.Bitmap) TypedArray(android.content.res.TypedArray) Resources(android.content.res.Resources) Layers(org.mapsforge.map.layer.Layers) LatLong(org.mapsforge.core.model.LatLong) Location(android.location.Location)

Example 9 with LatLong

use of org.mapsforge.core.model.LatLong in project satstat by mvglasow.

the class MapSectionFragment method onCreateView.

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    mainActivity = (MainActivity) this.getContext();
    View rootView = inflater.inflate(R.layout.fragment_main_map, container, false);
    float density = this.getContext().getResources().getDisplayMetrics().density;
    String versionName;
    try {
        versionName = mainActivity.getPackageManager().getPackageInfo(mainActivity.getPackageName(), 0).versionName;
    } catch (NameNotFoundException e) {
        versionName = "unknown";
    }
    mapReattach = (ImageButton) rootView.findViewById(R.id.mapReattach);
    mapAttribution = (TextView) rootView.findViewById(R.id.mapAttribution);
    mapReattach.setVisibility(View.GONE);
    isMapViewAttached = true;
    OnClickListener clis = new OnClickListener() {

        @Override
        public void onClick(View v) {
            if (v == mapReattach) {
                isMapViewAttached = true;
                mapReattach.setVisibility(View.GONE);
                updateMap();
            }
        }
    };
    mapReattach.setOnClickListener(clis);
    // Initialize controls
    mapMap = new MapView(rootView.getContext());
    ((FrameLayout) rootView).addView(mapMap, 0);
    mapMap.setClickable(true);
    mapMap.getMapScaleBar().setVisible(true);
    mapMap.getMapScaleBar().setMarginVertical((int) (density * 16));
    mapMap.setBuiltInZoomControls(true);
    mapMap.getMapZoomControls().setZoomLevelMin((byte) 10);
    mapMap.getMapZoomControls().setZoomLevelMax((byte) 20);
    mapMap.getMapZoomControls().setZoomControlsOrientation(Orientation.VERTICAL_IN_OUT);
    mapMap.getMapZoomControls().setZoomInResource(R.drawable.zoom_control_in);
    mapMap.getMapZoomControls().setZoomOutResource(R.drawable.zoom_control_out);
    mapMap.getMapZoomControls().setMarginHorizontal((int) (density * 8));
    mapMap.getMapZoomControls().setMarginVertical((int) (density * 16));
    providerLocations = new HashMap<String, Location>();
    mAvailableProviderStyles = new ArrayList<String>(Arrays.asList(Const.LOCATION_PROVIDER_STYLES));
    providerStyles = new HashMap<String, String>();
    providerAppliedStyles = new HashMap<String, String>();
    providerInvalidationHandler = new Handler();
    providerInvalidators = new HashMap<String, Runnable>();
    onlineTileSource = new OnlineTileSource(Const.TILE_SERVER_OSM, 80);
    onlineTileSource.setUserAgent(String.format("%s/%s (%s)", "SatStat", versionName, System.getProperty("http.agent")));
    onlineTileSource.setName(Const.TILE_CACHE_OSM).setAlpha(false).setBaseUrl(Const.TILE_URL_OSM).setExtension(Const.TILE_EXTENSION_OSM).setParallelRequestsLimit(8).setProtocol("http").setTileSize(256).setZoomLevelMax((byte) 18).setZoomLevelMin((byte) 0);
    GestureDetector gd = new GestureDetector(rootView.getContext(), new GestureDetector.SimpleOnGestureListener() {

        public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
            mapReattach.setVisibility(View.VISIBLE);
            isMapViewAttached = false;
            return false;
        }
    });
    mapMap.setGestureDetector(gd);
    mainActivity.mapSectionFragment = this;
    float lat = mainActivity.mSharedPreferences.getFloat(Const.KEY_PREF_MAP_LAT, 360.0f);
    float lon = mainActivity.mSharedPreferences.getFloat(Const.KEY_PREF_MAP_LON, 360.0f);
    if ((lat < 360.0f) && (lon < 360.0f)) {
        mapMap.getModel().mapViewPosition.setCenter(new LatLong(lat, lon));
    }
    int zoom = mainActivity.mSharedPreferences.getInt(Const.KEY_PREF_MAP_ZOOM, 16);
    mapMap.getModel().mapViewPosition.setZoomLevel((byte) zoom);
    createLayers(true);
    return rootView;
}
Also used : OnlineTileSource(org.mapsforge.map.layer.download.tilesource.OnlineTileSource) NameNotFoundException(android.content.pm.PackageManager.NameNotFoundException) Handler(android.os.Handler) GestureDetector(android.view.GestureDetector) View(android.view.View) TextView(android.widget.TextView) MapView(org.mapsforge.map.android.view.MapView) Point(org.mapsforge.core.model.Point) Paint(org.mapsforge.core.graphics.Paint) MotionEvent(android.view.MotionEvent) FrameLayout(android.widget.FrameLayout) OnClickListener(android.view.View.OnClickListener) MapView(org.mapsforge.map.android.view.MapView) LatLong(org.mapsforge.core.model.LatLong) Location(android.location.Location)

Example 10 with LatLong

use of org.mapsforge.core.model.LatLong in project satstat by mvglasow.

the class MapSectionFragment method onLocationChanged.

/**
 * Called when a new location is found by a registered location provider.
 * Stores the location and updates GPS display and map view.
 */
public void onLocationChanged(Location location) {
    // location from that provider as stale
    if (Double.isNaN(location.getLatitude()) || Double.isNaN(location.getLongitude())) {
        markLocationAsStale(providerLocations.get(location.getProvider()));
        applyLocationProviderStyle(this.getContext(), location.getProvider(), Const.LOCATION_PROVIDER_GRAY);
        return;
    }
    if (providerLocations.containsKey(location.getProvider()))
        providerLocations.put(location.getProvider(), new Location(location));
    LatLong latLong = new LatLong(location.getLatitude(), location.getLongitude());
    Circle circle = mapCircles.get(location.getProvider());
    Marker marker = mapMarkers.get(location.getProvider());
    if (circle != null) {
        circle.setLatLong(latLong);
        if (location.hasAccuracy()) {
            circle.setVisible(true);
            circle.setRadius(location.getAccuracy());
        } else {
            Log.d("MainActivity", "Location from " + location.getProvider() + " has no accuracy");
            circle.setVisible(false);
        }
    }
    if (marker != null) {
        marker.setLatLong(latLong);
        marker.setVisible(true);
    }
    applyLocationProviderStyle(this.getContext(), location.getProvider(), null);
    Runnable invalidator = providerInvalidators.get(location.getProvider());
    if (invalidator != null) {
        providerInvalidationHandler.removeCallbacks(invalidator);
        providerInvalidationHandler.postDelayed(invalidator, PROVIDER_EXPIRATION_DELAY);
    }
    // redraw, move locations into view and zoom out as needed
    if ((circle != null) || (marker != null) || (invalidator != null))
        updateMap();
}
Also used : Circle(org.mapsforge.map.layer.overlay.Circle) Marker(org.mapsforge.map.layer.overlay.Marker) LatLong(org.mapsforge.core.model.LatLong) Location(android.location.Location)

Aggregations

LatLong (org.mapsforge.core.model.LatLong)12 Location (android.location.Location)6 Point (org.mapsforge.core.model.Point)4 Marker (org.mapsforge.map.layer.overlay.Marker)4 Paint (org.mapsforge.core.graphics.Paint)3 TileDownloadLayer (org.mapsforge.map.layer.download.TileDownloadLayer)3 TileRendererLayer (org.mapsforge.map.layer.renderer.TileRendererLayer)3 Context (android.content.Context)2 Intent (android.content.Intent)2 Drawable (android.graphics.drawable.Drawable)2 Uri (android.net.Uri)2 Bundle (android.os.Bundle)2 View (android.view.View)2 Window (android.view.Window)2 MapDataStore (org.mapsforge.map.datastore.MapDataStore)2 AbstractTileSource (org.mapsforge.map.layer.download.tilesource.AbstractTileSource)2 Circle (org.mapsforge.map.layer.overlay.Circle)2 Manifest (android.Manifest)1 Activity (android.app.Activity)1 SharedPreferences (android.content.SharedPreferences)1