how to use googlemap in fragment android? [duplicate] - android

This question already has answers here:
Using Google Maps inside a Fragment in Android
(2 answers)
Closed 7 years ago.
I find a tutorial accroding getmap() in stackoverflow but it was for old version.
this is new offical google tutorial for create map:
public class mapmain extends FragmentActivity implements OnMapReadyCallback {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.primary_layout);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap map) {
// Add a marker in Sydney, Australia, and move the camera.
LatLng sydney = new LatLng(-34, 151);
map.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
map.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
}
how can I convert it to fragment class? (extend by fragment not FragmentActivity)

How to put Google Maps V2 on a Fragment
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.MapsInitializer;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
/**
* A fragment that launches other parts of the demo application.
*/
public class MapFragment extends Fragment {
MapView mMapView;
private GoogleMap googleMap;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// inflat and return the layout
View v = inflater.inflate(R.layout.fragment_location_info, container,
false);
mMapView = (MapView) v.findViewById(R.id.mapView);
mMapView.onCreate(savedInstanceState);
mMapView.onResume();// needed to get the map to display immediately
try {
MapsInitializer.initialize(getActivity().getApplicationContext());
} catch (Exception e) {
e.printStackTrace();
}
googleMap = mMapView.getMap();
// latitude and longitude
double latitude = 17.385044;
double longitude = 78.486671;
// create marker
MarkerOptions marker = new MarkerOptions().position(
new LatLng(latitude, longitude)).title("Hello Maps");
// Changing marker icon
marker.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_ROSE));
// adding marker
googleMap.addMarker(marker);
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(17.385044, 78.486671)).zoom(12).build();
googleMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
// Perform any camera updates here
return v;
}
#Override
public void onResume() {
super.onResume();
mMapView.onResume();
}
#Override
public void onPause() {
super.onPause();
mMapView.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
mMapView.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mMapView.onLowMemory();
}
}
fragment_location_info.xml
<?xml version="1.0" encoding="utf-8"?>
<com.google.android.gms.maps.MapView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/mapView"
android:layout_width="match_parent"
android:layout_height="match_parent" />

Related

How do I update the marker within Google Maps? [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
In the below code, I am able to create a marker on the map. Whenever I try to run it with the runnable, I get the error stating to googleMap with the error as:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.journaldev.MapsInAction/com.journaldev.MapsInAction.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.android.gms.maps.model.Marker com.google.android.gms.maps.GoogleMap.addMarker(com.google.android.gms.maps.model.MarkerOptions)' on a null object reference
The code is as follows:
import android.graphics.Point;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.view.animation.Interpolator;
import android.view.animation.LinearInterpolator;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.Projection;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
public class MainActivity extends AppCompatActivity implements OnMapReadyCallback {
SupportMapFragment mapFragment;
private GoogleMap googleMap;
double latitude=12.9716;
double longitude=77.5946;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mapFragment.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap googleMap) {
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
googleMap.addMarker(new MarkerOptions()
.position(new LatLng(latitude, longitude))
.title("Bus Location")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)));
googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude, longitude), 15));
}
});
}
});
periodicUpdate.run();
}
Handler handler = new Handler();
private Runnable periodicUpdate = new Runnable() {
#Override
public void run() {
handler.postDelayed(periodicUpdate, 10*1000 - SystemClock.elapsedRealtime()%1000);
latitude+=0.01;
longitude+=0.01;
MarkerOptions a = new MarkerOptions()
.position(new LatLng(50,6));
Marker m = googleMap.addMarker(a);
m.setPosition(new LatLng(50,5));
}
};
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onMapReady(GoogleMap googleMap)
{
googleMap.addMarker(new MarkerOptions()
.position(new LatLng(latitude, longitude))
.title("Bus Location")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)));
googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude, longitude), 15));
}
}
How do I make sure that the code also updates the marker every 10 seconds? If the Runnable code is removed, it works perfectly with the marker shown. With the Runnable code, it crashes with the error above.
getMapAsync initialize Map asynchronously.
So when you call googleMap.addMarker() at first time in your Runnable it crashes because Map is not initialized yet and googleMap is null.
Easiest way to fix this is move periodicUpdate.run(); to onMapReady() callback
Also you must not forget to clean Runnable in onPause()
You are putting marker before map is initialized in runnable. That is why it is causing null pointer exception and crashing app. Putting a null pointer check will resolve this error. Try this:
#Override
public void run() {
handler.postDelayed(periodicUpdate, 10 * 1000 - SystemClock.elapsedRealtime() % 1000);
latitude += 0.01;
longitude += 0.01;
MarkerOptions a = new MarkerOptions()
.position(new LatLng(50, 6));
if (googleMap != null) {
Marker m = googleMap.addMarker(a);
}
m.setPosition(new LatLng(50, 5));
}
There are several issues with your code.
At first, it crashes because in periodicUpdate.run(); you try to create marker (Marker m = googleMap.addMarker(a);) by calling addMarker() on global private GoogleMap googleMap; object which is not initialized. It will be better if you rename private GoogleMap googleMap; to private GoogleMap mGoogleMap; and init mGoogleMap in onMapReady(GoogleMap googleMap) by mGoogleMap = googleMap nd than call addMarker() on it: Marker mGoogleMap = googleMap.addMarker(a);.
Also, you should get rid of two onMapReady() methods. And you should start call periodicUpdate.run(); inside onMapReady() because in other case its possible that the Marker m = mGoogleMap.addMarker(a); can be called before mGoogleMap was created. And you should declare Marker m as global (private Marker mMarker) for possibility to remove it before create updated marker. And seems you didn't update LatLng of marker... So, there are a lot of work...
You haven't initialed the variable googleMap yet. And before using googleMap, you have to make sure Google Map is ready. So follow this code:
private Runnable periodicUpdate = new Runnable() {
#Override
public void run() {
handler.postDelayed(periodicUpdate, 10*1000 - SystemClock.elapsedRealtime()%1000);
if(googleMap){
latitude+=0.01;
longitude+=0.01;
MarkerOptions a = new MarkerOptions()
.position(new LatLng(50,6));
Marker m = googleMap.addMarker(a);
m.setPosition(new LatLng(50,5));
}
}
};
#Override
public void onMapReady(GoogleMap googleMap)
{
this.googleMap = googleMap;
googleMap.addMarker(new MarkerOptions()
.position(new LatLng(latitude, longitude))
.title("Bus Location")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)));
googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude, longitude), 15));
}

How to add unlimited markers on click - google maps api

I'm developing an application using Google Maps API.
I'm trying to add a marker where the user press on the map and to draw a line between markers that the user have created.
I'v tried to add the method SetOnMapClickListener but every time I run my application in the virtual device it's immediately crushes.
I've also tried to locate the method in OnCreate method and in OnMapReady, but this is not working either.
I succeeded to add new markers but only by writing them...
On some tutorials that I've found I saw that they assign the google map object with mapFragment.getMap(), but I don't have this method.
Thanks!
Here is my code:
package com.example.user.testmap;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng latLng) {
double lit = latLng.latitude;
double lon = latLng.longitude;
mMap.addMarker(new MarkerOptions().position(new LatLng(lit, lon)));
}
});
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
mMap.addMarker(new MarkerOptions().position(new LatLng(20, 5)));
mMap.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(20, 5)));
}
}
try to remove your mMap.setOnMapClickListener in onCreate() then implements the GoogleMap.OnMapClickListener
like this.
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleMap.OnMapClickListener {
private GoogleMap mMap;
private ArrayList<Marker> arrMarkerList;
private ArrayList<Polyline> arrPolylineList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setOnMapClickListener(this);
arrMarkerList = new ArrayList<>();
arrPolylineList = new ArrayList<>();
}
#Override
public void onMapClick(LatLng latLng) {
double lit = latLng.latitude;
double lon = latLng.longitude;
arrMarkerList.add(mMap.addMarker(new MarkerOptions().position(new LatLng(lit, lon))));
// Removing the existing polyline to draw a new.
for (Polyline polyline : arrPolylineList) {
polyline.remove();
}
if (arrMarkerList.size() > 1) {
PolylineOptions polylineOptions = new PolylineOptions();
for (Marker marker : arrMarkerList) {
polylineOptions.add(marker.getPosition());
}
arrPolylineList.add(mMap.addPolyline(polylineOptions));
}
}
}

Android Google Map set Style Map with json

i have develop a simple app and i have integrate a google map using this simple way:`
mapFragment.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap googleMap) {
mClusterManager = new ClusterManager<Car2GoClusterItem>(getActivity(), map);
map.setOnCameraChangeListener(mClusterManager);
map.setInfoWindowAdapter(mClusterManager.getMarkerManager());
map.setOnMarkerClickListener(mClusterManager);
mClusterManager.setOnClusterItemClickListener(
new ClusterManager.OnClusterItemClickListener<Car2GoClusterItem>() {
#Override
public boolean onClusterItemClick(Car2GoClusterItem item) {
clickedClusterItem = item;
return false;
}
});
});
}
public GoogleMap.OnCameraChangeListener getCameraChangeListener() {
return new GoogleMap.OnCameraChangeListener() {
#Override
public void onCameraChange(CameraPosition position) {
Log.d("Zoom", "Zoom: " + position.zoom);
if (previousZoomLevel <= 15 && position.zoom > 15) {
map.clear();
processMap(v, 16);
}
if (previousZoomLevel >= 15 && position.zoom < 15) {
map.clear();
processMap(v, 14);
}
previousZoomLevel = position.zoom;
}
};
}
public void processMap(View v, int zoom) {
if (map == null) {
map = ((SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map))
.getMap();
}
if (map != null) {
//// code here
}
}
Now i would like to set for my map a specific MapStyle by json and i have seen this code:
public void onMapReady(GoogleMap googleMap) {
// Customise the styling of the base map using a JSON object defined
// in a string resource file. First create a MapStyleOptions object
// from the JSON styles string, then pass this to the setMapStyle
// method of the GoogleMap object.
boolean success = googleMap.setMapStyle(new MapStyleOptions(getResources()
.getString(R.string.style_json)));
if (!success) {
Log.e(TAG, "Style parsing failed.");
}
// Position the map's camera near Sydney, Australia.
googleMap.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(-34, 151)));
}
but i don't know how to integrate because this sample is for activity instead i use a fragment and also when i tryto add this code give me a error.
Any help?
thanks
After a good research and code I implemented Google Map in fragment using the following code:
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import java.util.ArrayList;
public class MapFragment extends Fragment implements OnMapReadyCallback{
public MapFragment() {
// Required empty public constructor
}
private MapView mapView;
private GoogleMap googleMap;
View rootView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_map, container, false);
SupportMapFragment mapFragment = (SupportMapFragment) getActivity().getSupportFragmentManager().findFragmentById(R.id.map);
return rootView;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mapView = (MapView) view.findViewById(R.id.map);
mapView.onCreate(savedInstanceState);
mapView.onResume();
mapView.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap map) {
googleMap = map;
googleMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
googleMap.setMinZoomPreference(12.6f);
googleMap.getUiSettings().setAllGesturesEnabled(true);
}
}
Following is the xml code which I am using for map fragment
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.gms.maps.MapView
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</android.support.design.widget.CoordinatorLayout>
In this fragment you can volley can get JSON and style your map accordingly.

I'm using the google maps v2 API and when I going to get the map with the getMap method it returns null

This is Fragment class....
public class LocationFragment extends Fragment {
GoogleMap googleMap=null;
Location_Manager lm=new Location_Manager();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_location, container, false);
googleMap=lm.init();
return v;
}
}
and I call Location_Manager class ans use init() Method....
public class Location_Manager extends FragmentActivity{
GoogleMap googleMap=null;
FragmentManager fm;
SupportMapFragment smf;
Handler handler=new Handler();
public Location_Manager() {
// TODO Auto-generated constructor stub
}
public GoogleMap init(){
fm=getSupportFragmentManager();
smf = (SupportMapFragment) fm.findFragmentById(R.id.google_map);
new Handler().postDelayed(new Runnable(){
#Override
public void run() {
// TODO Auto-generated method stub
googleMap =smf.getMap();
googleMap.addMarker(new MarkerOptions().position(new LatLng(37, 123)).title("sample"));
}
}, 500);
return googleMap;
}
}
googleMap =smf.getMap(); has error.. log show me that googleMap is null...
I already used handler and Supportmapfragment but I can't solve this problem..
How can I solve???
plz help me;
Try to follow the Getting started on Android Google Developer site https://developers.google.com/maps/documentation/android/map
You can also look into the examples in the extras like that:
package com.example.mapdemo;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
/**
* This shows how to create a simple activity with a map and a marker on the map.
*/
public class BasicMapDemoActivity extends FragmentActivity implements OnMapReadyCallback {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.basic_demo);
SupportMapFragment mapFragment =
(SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
/**
* This is where we can add markers or lines, add listeners or move the camera. In this case, we
* just add a marker near Africa.
*/
#Override
public void onMapReady(GoogleMap map) {
map.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));
}
}

Cannot cast form Fragment to Mapfragment

i Want to make maps in android, this is for My Skripsi, i Download Source code in here https://github.com/ajaswal/GoogleMapsV2 i strat open project, but have proble this is my problem, i have alert about cannot cast from Fragment to MapFragment, this problem in line 27.
map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
so please help me...
package com.example.googlemaps;
import android.app.Activity;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.LatLng;
public class MainActivity extends Activity {
public final LatLng LOCATION_BURNABY= new LatLng(49.27645, -122.917587);
public final LatLng LOCATION_SURREY= new LatLng(49.187500, -122.849000);
private GoogleMap map;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
if (map != null) {
setUpMap();
}
}
private void setUpMap() {
// Enable MyLocation layer of Google map
map.setMyLocationEnabled(true);
// Get Location manager object from System service LOCATION_SERVICE
LocationManager locManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// Create a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Get the name of the best provider
String provider = locManager.getBestProvider(criteria, true);
// Get current location
Location myLocation = locManager.getLastKnownLocation(provider);
// Set map type
map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
// Get the latitude of the current location
double latitude = myLocation.getLatitude();
// Get the longitude of the current location
double longitude = myLocation.getLongitude();
// Create a LatLng object for the current location
LatLng LOCATION_CURRENT = new LatLng(latitude, longitude);
// Show the current location in Google map
map.moveCamera(CameraUpdateFactory.newLatLng(LOCATION_CURRENT));
// Zoom in the google map
CameraUpdate camUpdate = CameraUpdateFactory.newLatLngZoom(
LOCATION_CURRENT, 15);
map.animateCamera(camUpdate);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void onClick_Burnaby(View v){
map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
CameraUpdate update = CameraUpdateFactory.newLatLngZoom(LOCATION_BURNABY, 13);
map.animateCamera(update);
}
public void onClick_Surrey(View v){
map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
CameraUpdate update = CameraUpdateFactory.newLatLngZoom(LOCATION_SURREY, 14);
map.animateCamera(update);
}}
Use FragmentActivity instead of Activity
Example -
public class MapScreen extends FragmentActivity{
private GoogleMap map;
private Location location;
private ArrayList<LatLng> mLocationsLatLngList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map_screen);
map = ((SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.mapfragment)).getMap();
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(Your_CurrentLocation).zoom(13).bearing(0) // Sets the orientation of the camera to east
.tilt(30) // Sets the tilt of the camera to 30 degrees
.build(); // Creates a CameraPosition from the builder
map.setBuildingsEnabled(true);
map.setMyLocationEnabled(true);
map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
}
xml -
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<fragment
android:id="#+id/mapfragment"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
class="com.google.android.gms.maps.SupportMapFragment" />
</LinearLayout>
You are using SupportMapFragment in the XML, so you must use getSupportFragmentManager instead of getFragmentManager.
Use this code to obtain the Fragment and the Map:
SupportMapFragment fr = (SupportMapFragment)this.getSupportFragmentManager().findFragmentById(R.id.mapfragment);
GoogleMap Map = fr.getMap();
Your Activity must extend FragmentActivity.

Categories

Resources