Unable to get "mylocation" Google Maps Android - android

I am trying to get the "blue dot" my location coordinates and set it as the center of my initial mapview load. But I am getting a null pointer exception.
What am I missing here ?
public class GetLocationActivity extends MapActivity implements OnClickListener {
private MapView location;
private LocationMarker locationMarker;
private MyLocationOverlay locationOverlay;
private GeoPoint destination;
private GeoPoint source;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.location);
location = (MapView) this.findViewById(R.id.location);
location.setBuiltInZoomControls(true);
location.setClickable(true);
location.setLongClickable(true);
location.getController().setZoom(12);
locationMarker = new LocationMarker(this, location, marker,
(ImageView) findViewById(R.id.drag));
location.getOverlays().add(locationMarker);
locationOverlay = new MyLocationOverlay(this, location);
location.getOverlays().add(locationOverlay);
source = locationOverlay.getMyLocation();
location.getController().setCenter(
new GeoPoint(source.getLatitudeE6(), source.getLongitudeE6()));
}
Getting a nullPointer at source.getLatitudeE6().

Forgetting my basics here :). I need to get my location using LocationManager.
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0,
(LocationListener) this);

Related

How can draw a line(Polyline ) in Android studio in OSM (open map street)?

I want to draw a line in OSM between 2 points ,but i cant find anything that help me. something likes Polyline in googlemap.
public class MainActivity extends Activity {
private MapView mMapView;
private MapController mMapController;
public TextView textView;
public String longitude;
public String latitude;
public Drawable marker;
private ItemizedIconOverlay<OverlayItem> anotherItemizedIconOverlay;
ArrayList<OverlayItem> overlayItemArray;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.osm_main);
mMapView = (MapView) findViewById(mapview);
textView = (TextView) findViewById(R.id.textView);
mMapView.setTileSource(TileSourceFactory.DEFAULT_TILE_SOURCE);
mMapView.setBuiltInZoomControls(true);
mMapController = (MapController) mMapView.getController();
mMapController.setZoom(16);
Double latE6 = (52.507621 )* 1E6;
Double lngE6 = (13.407334 )* 1E6;
GeoPoint gPt = new GeoPoint(latE6.intValue(), lngE6.intValue());
mMapController.setCenter(gPt);
}
}
Well... just use the osmdroid Polyline.
GeoPoint gPt0 = new GeoPoint(52.507621d, 13.407334d);
GeoPoint gPt1 = new GeoPoint(52.527621d, 13.427334d);
Polyline line = new Polyline(this);
line .addPoint(gPt0);
line .addPoint(gPt1);
mMapView.getOverlays().add(line);
I place this code in onCreate after this line:
mMapController.setCenter(gPt);
GeoPoint gPt0 = new GeoPoint(52.507621d, 13.407334d);
GeoPoint gPt1 = new GeoPoint(52.527621d, 13.427334d);
PathOverlay myPath = new PathOverlay(Color.RED, this);
myPath.addPoint(gPt0);
myPath.addPoint(gPt1);
mMapView.getOverlays().add(myPath);
Note:Use d after your point .

Android Maps onLocationChanged problems

Im having problems with my current code, i don't see what i'm doing wrong. i keep getting the error "no suitable method found for requestLocationUpdates(string,int,in,MapsActivity)
public class MapsActivity extends AppCompatActivity implements LocationListener, OnMapReadyCallback, View.OnClickListener, DirectionCallback, OnMapClickListener, GoogleApiClient.OnConnectionFailedListener {
private LocationManager locationManager;
private Button btnRequestDirection;
GPSTracker gps;
private GoogleMap googleMap;
private String serverKey = "xxx";
private LatLng camera = new LatLng(54.1111, -1.1111);
private LatLng origin = new LatLng(54.1111, -1.1111);
private LatLng destination = new LatLng(54.11, -1.11);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
gps = new GPSTracker(MapsActivity.this);
long i = 1000;
long x = 10;
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,i,x, this);
if (gps.canGetLocation()) {
camera = new LatLng(gps.getLatitude(), gps.getLongitude());
origin = camera;
btnRequestDirection = (Button) findViewById(R.id.btn_request_direction);
btnRequestDirection.setOnClickListener(this);
((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMapAsync(this);
} else {
gps.showSettingsAlert();
}
}
Everything i do the event "onLocationChanged()" never triggers, =/
You need to have a locationListener to listen for a location changes. If you are using 'requestLocationUpdates', you must use 'import android.location.LocationListener'. The standard Android location stuffs is 'android.location'. The com.google.android.gms.location stuff is for use with the FusedLocationProviderApi which is part of Google play services.

How to get the location(LatLng/Name) in a google map at the centre of map

Guys I'm implementing google maps in my android app and instread of creating a marker i've placed a marker image in the middle of map. Now I want that whenever user drags the map i get the location at the centre of the map(where i've placed my image look like a marker).
My map activity is :
public class MapActivity extends FragmentActivity implements LocationListener {
private GoogleMap mMap; // Might be null if Google Play services APK is not available.
TextView Title;
FrameLayout goback;
Location myLocation;
LocationManager locationManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
setUpMapIfNeeded();
SupportMapFragment supportMapFragment =
(SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mMap = supportMapFragment.getMap();
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String bestProvider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(bestProvider);
if (location != null) {
onLocationChanged(location);
}
locationManager.requestLocationUpdates(bestProvider, 20000, 0, this);
//try
Title=(TextView)findViewById(R.id.map_title);
Title.setText(getIntent().getExtras().getString("Header"));
goback=(FrameLayout)findViewById(R.id.frame_layout);
setUpMapIfNeeded();
// mMap.setMyLocationEnabled(true);
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap();
}
}
}
private void setUpMap() {
}
#Override
public void onLocationChanged(Location location) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
BitmapDescriptor icon = BitmapDescriptorFactory.fromResource(R.drawable.marker);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(5));
CameraPosition ll=mMap.getCameraPosition();
Toast.makeText(getApplicationContext(),""+ll,Toast.LENGTH_LONG).show();
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
please help me in doing so, thank you :)
First you can get referance of your map container, and calculate center point by dividing 2 width and height.
View containerView=findViewById(R.id.mapContainer);
LatLng centerPoint= this.map.getProjection().fromScreenLocation(new Point(((int)containerView.getWidth/2),((int)(containerView.getHeight/2)));
you can get the center this way:
mMap.getCameraPosition().target
where mMap is the GoogleMap instance from your activity. This will return a LatLng object which basically represents the center of the map. Note that the GeoPoint class is not anymore available.
According to http://developer.android.com/reference/com/google/android/gms/maps/model/CameraPosition.html
target is "The location that the camera is pointing at." (tested it with the sample code and it worked ok for me)
Let me know if this helped you.
Cheers!
You can use this method
MapView.getProjection().fromPixels(x, y)
Where x is half your map width and y is half the height. This should return you a coordinates object which in turn will give you your longitude and latitude of the center of your map
More information on it can be seen here

Android google maps location manager not working in SupportMapFragment

I'm currently trying to include the google maps into my app. The main aim is to move the camera automatically to the current location of the device with a zoom after the map was loaded.
For this I need a location manager. In the below code I'm trying to implement one, but without success. I also tried to pass the context from a fragment class.
But still I'm getting this message from eclipse: The method getSystemService(String) is undefined for the type Navigation
Any ideas what I'm doing wrong?
public class Navigation extends SupportMapFragment {
private GoogleMap map;
private Context mContext;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View v = inflater.inflate(R.layout.activity_navigation, null, false);
getContextFromConfig();
setUpMapIfNeeded();
return v;
}
private void getContextFromConfig()
{
ContextConfig config = new ContextConfig();
mContext = config.getContext();
}
#Override
public void onResume() {
super.onResume();
setUpMapIfNeeded();
}
private void setUpMapIfNeeded() {
if (map == null) {
map = ((SupportMapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap();
} else {
System.out.println("Google Maps is not available.");
}
if (map != null) {
setUpMap();
}
}
private void setUpMap() {
map.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker").snippet("snippet"));
// Enable MyLocation Layer of Google Map
map.setMyLocationEnabled(true);
// Get LocationManager object from System Service LOCATION_SERVICE
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Create a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Get the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
// Get Current Location
Location myLocation = locationManager.getLastKnownLocation(provider);
//set map type
map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
// Get latitude of the current location
double latitude = myLocation.getLatitude();
// Get longitude of the current location
double longitude = myLocation.getLongitude();
// Create a LatLng object for the current location
LatLng latLng = new LatLng(latitude, longitude);
// Show the current location in Google Map
map.moveCamera(CameraUpdateFactory.newLatLng(latLng));
// Zoom in the Google Map
map.animateCamera(CameraUpdateFactory.zoomTo(14));
map.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title("You are here!"));
}
}
getSystemService() is a method of Context, not of Fragment. You probably want to do this:
LocationManager locationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
or this:
LocationManager locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);

onCreate wasn't called by the main class

I've read a lot of articles but none of them could fix my problem of not calling the onCreate-method in the class XMLParsingExample.
The log-statement in the onCreate didn't show output and tracing shows that the class is exited after boolean finished=false and thus not running the onCreate.
Here the codes:
public class MyMap extends MapActivity {
private MapView mapView;
private MapController mc;
private OverlayItem overlayItem;
private List<Overlay> mapOverlays;
private Drawable drawable;
private Drawable drawable2;
private MyItemizedOverlay itemizedOverlayMyLoc;
private MyItemizedOverlay itemizedOverlayRust;
private LocationManager locMgr;
private MyLocationListener locLstnr;XMLParsingExample mXMLParsingExample;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
mc = mapView.getController();
mapView.setBuiltInZoomControls(true);
locMgr = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
locLstnr = new MyLocationListener();
locMgr.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locLstnr);
mapOverlays = mapView.getOverlays();
// first overlay
drawable = getResources().getDrawable(R.drawable.marker2);
itemizedOverlayMyLoc = new MyItemizedOverlay(drawable, mapView);
// LAT LONG
GeoPoint uwLoc = new GeoPoint((int)(52.22778*1E6),(int)(6.10428*1E6));
overlayItem = new OverlayItem(uwLoc, "Uw locatie", "http://www.nu.nl");
itemizedOverlayMyLoc.addOverlay(overlayItem);
mapOverlays.add(itemizedOverlayMyLoc);
// Rustpunten overlay
drawable2 = getResources().getDrawable(R.drawable.rmarker3);
itemizedOverlayRust = new MyItemizedOverlay(drawable2, mapView);
mXMLParsingExample = new XMLParsingExample();
and here the class which where the oncreate isn't called:
public class XMLParsingExample extends Activity {
/** Create Object For SiteList Class */
public SitesList sitesList = null;
public ProgressDialog progressDialog;
boolean finished=false;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Log.i("onCreate", "onCreate started");
}
Starting a new Activity is not done by instantiating it (new XMLParsingExample();), but with an intent, for example:
Intent intent = new Intent(this, XMLParsingExample.class);
startActivity(intent);
Take a look at the here.
Binyamin Sharet is correct.
I think you are confusing a creator method, which does get called when you allocate an object, and onCreate(), which is an Android lifecycle callback function that gets called automatically by the framework at the appropriate time.
A creator function doesn't usually have 'create' in its name; it shares the name of the class whose object you are instantiating. In your case, the creator would be called XMLParsingExample().
For more information about Android lifecycle callbacks, see http://developer.android.com/guide/topics/fundamentals/activities.html.

Categories

Resources