I have a small map view in my contacts activity:
But I don't know how to move the camera to a specific location, I've done it before on a MapActivity, but don't know how to do it in here. I don't know where to use the moveCamera function because there is no onMapReady like in a MapActivity, appreciate any help guys. The code:
Java:
public class Contacts extends AppCompatActivity {
private GoogleMap mMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contacts);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("Contactos");
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
XML:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.LinearLayoutCompat 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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.abili.agriexport2.Contacts">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="25dp"
android:orientation="vertical"
tools:layout_editor_absoluteX="8dp"
tools:layout_editor_absoluteY="0dp">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="0.20">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/textView7"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginTop="25dp"
android:layout_weight="1"
android:text="Onde Estamos:"
android:textSize="18sp" />
<fragment
android:id="#+id/miniMap"
android:name="com.google.android.gms.maps.MapFragment"
android:layout_width="match_parent"
android:layout_height="300dp"
android:layout_weight="8" />
</LinearLayout>
</ScrollView>
</LinearLayout>
</android.support.v7.widget.LinearLayoutCompat>
Try this:
in xml:
<fragment
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
in code: Declare
static final LatLng Your_Location = new LatLng(23.81, 90.41); //Your LatLong
private GoogleMap mMap;
then inside OnCreate()
((SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map)).getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(Your_Location, 15)); //move camera to location
if (mMap != null) {
Marker hamburg = mMap.addMarker(new MarkerOptions().position(Your_Location));
}
// Rest of the stuff you need to do with the map
}
});
#alb You can use the same implementaion as you mentioned you have worked with onMapReadyCallback.
Here are some changes in your code as you have not instantiated the map it is displaying default view
public class Contacts extends AppCompatActivity implements OnMapReadyCallback {
private GoogleMap mMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contacts);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("Contactos");
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.miniMap);
mapFragment.getMapAsync(this);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.clear();
//Here locate and move your camera as required
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(locationLatLng, 16.0f));
}
}
Update xml by replacing the map fragment
<fragment
android:id="#+id/miniMap"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="300dp"
android:layout_weight="8"
/>
Try this code:
googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(Latitude, Longitude), 18));
As your map is pretty static you can get a cleaner code if you add the camera target and zoom to your XML. Simply add this to your <fragment> in your layout.xml (changing the coordinates and zoom level to suit your needs):
xmlns:map="http://schemas.android.com/apk/res-auto"
map:cameraTargetLat="40"
map:cameraTargetLng="-4"
map:cameraZoom="18"
tools:ignore="MissingPrefix"
Note: you need the tools:ignore="MissingPrefix" line to fix this Unexpected namespace "map" - Android Google Maps API
Write listener to mapfragment
MapFragment mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.miniMap);
mapFragment.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap googleMap) {
//write your moveCamera function here
}
});
Try using LocationManager and create marker in onLocationChanged listener
public void onLocationChanged(Location location) {
final LatLng latlng = new LatLng(location.getLatitude(),location.getLongitude());
createMarker(latlng);
}
private void createMarker(LatLng latlng) {
MarkerOptions markerOptions = null;
try {
markerOptions = new MarkerOptions().position(latlng).title("Title");
} catch (IOException e) {
e.printStackTrace();
}
final Marker marker = googleMap.addMarker(markerOptions);
}
After creating marker, I have used below code to animate marker when camera is moved:
final LatLngInterpolator latLngInterpolator = new LatLngInterpolator.LinearFixed();
final LatLng startPosition = marker.getPosition();
final Handler handler = new Handler();
final long start = SystemClock.uptimeMillis();
final Interpolator interpolator = new LinearInterpolator();
final float durationInMs = 3000;
handler.post(new Runnable() {
long elapsed;
float t;
float v;
#Override
public void run() {
// Calculate progress using interpolator
elapsed = SystemClock.uptimeMillis() - start;
t = elapsed / durationInMs;
v = interpolator.getInterpolation(t);
marker.setPosition(latLngInterpolator.interpolate(v, startPosition, googleMap.getCameraPosition().target));
if (t < 1) {
// Post again 16ms later.
handler.postDelayed(this, 16);
}
}
});
Related
I create fragment with google map.
but when I want to delete marker from the map, I can not do this. I try everything and nothing help me. the marker relay delete but still shown on map what is the error in my code?
MapFragment.java
HashMap<String, BaseMarker> mAllMarkers = new HashMap<>();
private GoogleMap mMap;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
try {
mRoot = inflater.inflate(R.layout.fragment_map, null);
} catch (InflateException e) {
/* map is already there, just return view as it is */
}
mMap = null;
mMap = ((SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map))
.getMap();
for (final BaseMarker entry : baseMarkers) {//list of markers
Marker marker = mMap.addMarker(markerFactory.getMeetingPointCreateMarker(getActivity(), (MeetingPoint) entry));
marker.showInfoWindow();
entry.setMarker(marker);
mAllMarkers.put(entry.getMarkerId(), entry);
}
mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(final Marker marker) {
removeMarker();
}
});
return mRoot;
}
public removeMarker(){//this call when I click in marker
for (Map.Entry<String, BaseMarker> entry : mAllMarkers.entrySet()) {
BaseMarker marker = entry.getValue();
if (marker.getMarker() != null) {
marker.getMarker().remove();
mAllMarkers.remove(marker.getMarkerId());
}
}
}
my mapFragment.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/mapFooter">
<fragment
android:id="#+id/map"
class="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
You are removing all the markers right after you added them. You are doing this when the view isn't even completely loaded.
There's a simpler way , just call marker.remove() like this:
mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
marker.remove();
return false;
}
});
Also concider calling marker.setVisible(false) instead to prevent it from re-appearing.
I am adding SupportMapFragment programmatically to my main activity.
I am able to add it but i need a edit text and a button also to be displayed at the top of the map.
I have created a separate layout for my map fragment which i add programmatically inside my main activity. But i get a NPE saying "Unable to resume activity"
Please help me.
Here is my code . MainActivity.java
public class MainActivity extends FragmentActivity{
protected LocationManager locationManager;
protected LocationListener locationListener;
protected Context context;
GoogleMap googleMap;
String lat;
String provider;
protected double latitude,longitude;
protected boolean gps_enabled,network_enabled;
private ImageView mImage;
List<Marker> markerslist = new ArrayList<Marker>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// get an instance of FragmentTransaction from your Activity
final FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
//add a fragment
MapFragmentActivity mapFragment = new MapFragmentActivity();
fragmentTransaction.replace(R.id.appfragment, mapFragment);
fragmentTransaction.commit();
mImage = (ImageView)findViewById(R.id.eemaView);
mImage.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
System.out.println("inside on click eema");
EnterpriseFragment entFragment = new EnterpriseFragment();
FragmentTransaction fragmentTrans = fragmentManager.beginTransaction();
fragmentTrans.replace(R.id.appfragment, entFragment);
fragmentTrans.commit();
}
});
mImage = (ImageView)findViewById(R.id.deviationView);
mImage.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
System.out.println("inside on click deviation");
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
//add a fragment
MapFragmentActivity mapFragment = new MapFragmentActivity();
fragmentTransaction.replace(R.id.appfragment, mapFragment);
fragmentTransaction.commit();
}
});
}
Here is my fragment class
public class MapFragmentActivity extends SupportMapFragment implements LocationListener{
protected LocationManager locationManager;
protected LocationListener locationListener;
protected Context context;
GoogleMap googleMap;
String lat;
String provider;
protected double latitude,longitude;
protected boolean gps_enabled,network_enabled;
List<Marker> markerslist = new ArrayList<Marker>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.mapfragmentlayout, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
googleMap = this.getMap();
if (googleMap != null) {
//Your initialization code goes here
googleMap.setMyLocationEnabled(true);
LocationManager locationManager = (LocationManager) getActivity().getSystemService(getActivity().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);
// Getting reference to btn_find of the layout activity_main
//Button btn_find = (Button) getActivity().findViewById(R.id.btn_find);
// Defining button click event listener for the find button
View.OnClickListener findClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
// Getting reference to EditText to get the user input location
EditText etLocation = (EditText) getActivity().findViewById(R.id.et_location);
// Getting user input location
String location = etLocation.getText().toString();
if(location!=null && !location.equals("")){
for(Marker m : markerslist) {
System.out.println("Marker size is "+markerslist.size());
System.out.println("Title is "+m.getSnippet());
System.out.println("Position is "+((LatLng)(m.getPosition())).latitude);
if(location.equals(m.getSnippet())) {
// do something with the marker
LatLng latLng = m.getPosition();
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
break; // stop the loop
}
}
}
}
};
// Setting button click event listener for the find button
//btn_find.setOnClickListener(findClickListener);
googleMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
#Override
public View getInfoWindow(Marker marker) {
return null;
}
#Override
public View getInfoContents(Marker marker) {
// Getting view from the layout file info_window_layout
View v = getActivity().getLayoutInflater().inflate(R.layout.site_info_window, null);
List<String> qfList = JSONReader.readQuickFixData(getActivity());
ListView devLst = (ListView)v.findViewById(R.id.deviationList);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),R.layout.simple_list_item_deviation,android.R.id.text1,qfList);
devLst.setAdapter(adapter);
return v;
}
});
}
}
This is my fragment layout xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<Button
android:id="#+id/btn_find"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Find"
android:layout_alignParentRight="true" />
<EditText
android:id="#+id/et_location"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="text"
android:hint="Enter Site ID"
android:layout_toLeftOf="#id/btn_find" />
</RelativeLayout>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"/>
</LinearLayout>
My main layout xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="WEM App"
android:id="#+id/textView"
android:textStyle="bold"
android:textSize="16sp"
android:layout_gravity="center_horizontal"
android:gravity="center"
android:layout_margin="3dp"
android:textColor="#color/abc_input_method_navigation_guard"
android:background="#android:color/holo_green_light"/>
<LinearLayout
android:id="#+id/appfragment"
android:layout_width="match_parent"
android:layout_weight="4"
android:layout_height="0dip"
android:orientation="horizontal">
</LinearLayout>
<HorizontalScrollView
android:id="#+id/hsview1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:layout_marginBottom="3dp"
android:background="#android:color/holo_green_light">
<LinearLayout android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/deviationView"
android:layout_width="60dp"
android:layout_height="60dp"
android:src="#drawable/sema_icon" />
<ImageView
android:id="#+id/eemaView"
android:layout_width="60dp"
android:layout_height="60dp"
android:src="#drawable/eema_icon" />
<ImageView
android:id="#+id/siteView"
android:layout_width="60dp"
android:layout_height="60dp"
android:src="#drawable/sema_icon" />
<ImageView
android:id="#+id/alertsView"
android:layout_width="60dp"
android:layout_height="60dp"
android:src="#drawable/eema_icon" />
</LinearLayout>
</HorizontalScrollView>
</LinearLayout>
Make sure u r using import android.support.v4.app.Fragment; and import android.support.v4.app.FragmentTransaction;
Make changes as below -
change public class MapFragmentActivity extends SupportMapFragment
to public class MapFragmentActivity extends Fragment keep rest as it is.
I am having a problem initializing my map. The map fragment is inflated into the FrameLayout of the main activity. I keep getting a null pointer exception within the setUpMapIfNeeded() method.
activity_main.xml
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
`
<include layout="#layout/toolbar"/>
<FrameLayout
android:id="#+id/frameLayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"></FrameLayout>
</LinearLayout>
<android.support.design.widget.NavigationView
android:id="#+id/navigation_view"
android:layout_height="match_parent"
android:layout_width="wrap_content"
android:layout_gravity="start"
app:headerLayout="#layout/header"
app:menu="#menu/drawer"
/>
</android.support.v4.widget.DrawerLayout>
map_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/map"
tools:context=".MapFragment"
android:name="com.google.android.gms.maps.SupportMapFragment"/>
</LinearLayout>
MainActivity.java
switch (menuItem.getItemId()) {
case R.id.shop:
MapFragment mapFragment = new MapFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.frameLayout,mapFragment);
fragmentTransaction.commit();
break;
case R.id.list:
ListFragment listFragment = new ListFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction1 = getSupportFragmentManager().beginTransaction();
fragmentTransaction1.replace(R.id.frameLayout,listFragment);
fragmentTransaction1.commit();
break;
case R.id.points:
Toast.makeText(getApplicationContext(),"Global card selected",Toast.LENGTH_SHORT).show();
break;
}
return true;
}
});
MapFragment.java
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.map_fragment,container,false);
//Check if GPS is enabled
locationManager = (LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE);
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
Toast.makeText(getContext(),"GPS enabled",Toast.LENGTH_SHORT).show();
}else {
showGPSDisabledAlertToUser();
}
setUpMapIfNeeded();
return view;
}
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.
//I get a null pointer exception at this point, no map it gotten
mMap = ((SupportMapFragment)getActivity().getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap();
}
}
}
Take look at my repo for mapTab here. It shows how to initial the google map for in the fragment.
Sample code:
public class MapTabFragment extends Fragment {
private SupportMapFragment mMapView;
public static MapTabFragment newInstance(String param1, String param2) {
MapTabFragment fragment = new MapTabFragment();
return fragment;
}
MapView mapView;
GoogleMap map;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_map, container, false);
// Gets the MapView from the XML layout and creates it
MapsInitializer.initialize(getActivity());
switch (GooglePlayServicesUtil.isGooglePlayServicesAvailable(getActivity())) {
case ConnectionResult.SUCCESS:
Toast.makeText(getActivity(), "SUCCESS", Toast.LENGTH_SHORT).show();
mapView = (MapView) v.findViewById(R.id.map);
mapView.onCreate(savedInstanceState);
// Gets to GoogleMap from the MapView and does initialization stuff
if (mapView != null) {
map = mapView.getMap();
map.getUiSettings().setMyLocationButtonEnabled(false);
map.setMyLocationEnabled(true);
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new LatLng(43.1, -87.9), 10);
map.animateCamera(cameraUpdate);
}
break;
case ConnectionResult.SERVICE_MISSING:
Toast.makeText(getActivity(), "SERVICE MISSING", Toast.LENGTH_SHORT).show();
break;
case ConnectionResult.SERVICE_VERSION_UPDATE_REQUIRED:
Toast.makeText(getActivity(), "UPDATE REQUIRED", Toast.LENGTH_SHORT).show();
break;
default:
Toast.makeText(getActivity(), GooglePlayServicesUtil.isGooglePlayServicesAvailable(getActivity()), Toast.LENGTH_SHORT).show();
}
// Updates the location and zoom of the MapView
LatLng sydney = new LatLng(-33.867, 151.206);
map.setMyLocationEnabled(true);
map.moveCamera(CameraUpdateFactory.newLatLngZoom(sydney, 13));
map.addMarker(new MarkerOptions()
.title("Sydney")
.snippet("The most populous city in Australia.")
.position(sydney));
return v;
}
#Override
public void onResume() {
mapView.onResume();
super.onResume();
}
#Override
public void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
}
XML for this:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
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:name="com.bojie.materialtest.fragments.UpcomingFragment"/>
</RelativeLayout>
I am trying to switch fragments after login, I have MainActivity that for the first time add the LogIn Fragment to his content, after the user login, I want to switch to a Google map Fragment.
How can I create a Google Map class extending Fragment and not FragmentActivity or Activity?
Can I add FragmentActivity to the layout of the MainActivity?
/**
* Fragment that appears in the "content_frame", shows a planet
*/
public class YS_MapFragment extends Fragment {
public static final String ARG_PLANET_NUMBER = "planet_number";
public YS_MapFragment() {
// Empty constructor required for fragment subclasses
}
MarkerOptions markerOptions;
LatLng latLng;
String locationString;
MapView mapView;
GoogleMap googleMap;
private String tag = "TAG";
private String msg = "= ";
// GPSTrackerN class
GPSTracker gps;
double latitude = 0.0, longitude = 0.0;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View mainLayout = inflater.inflate(R.layout.fragment_map, container,false);
locationString = getArguments().getString("location");
latitude = getArguments().getDouble("Lat");
longitude = getArguments().getDouble("Long");
// Gets the MapView from the XML layout and creates it
mapView = (MapView) mainLayout.findViewById(R.id.mapview);
mapView.onCreate(savedInstanceState);
// Gets to GoogleMap from the MapView and does initialization stuff
googleMap = mapView.getMap();
googleMap.getUiSettings().setMyLocationButtonEnabled(false);
googleMap.setMyLocationEnabled(true);
// Needs to call MapsInitializer before doing any CameraUpdateFactory
// calls
MapsInitializer.initialize(this.getActivity());
if (locationString != null && !locationString.equals(""))
{
getLocation(latitude, longitude);
} else {
getCurrentLocation();
}
return mainLayout;
}
#Override
public void onResume() {
mapView.onResume();
super.onResume();
}
#Override
public void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
}
<RelativeLayout
android:id="#+id/RelativeLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<com.google.android.gms.maps.MapView
android:id="#+id/mapview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_marginBottom="40dip" >
</com.google.android.gms.maps.MapView>
I tried instantiating the map directly in the xml but it got me a lot of problems when trying to do more complex things with the fragments and the navigation.
The solution that gave me the best results is something like this:
1- Have an empty FrameLayout in my view's xml:
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_above="#id/color_separator" >
<FrameLayout
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:id="#+id/mapframe" />
</RelativeLayout>
2- Instantiate the SupportMapFragment in my Fragment class and add it to the FrameLayout:
if(mMapFragment==null) {
mMapFragment = SupportMapFragment.newInstance();
FragmentTransaction fragmentTransaction = getChildFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.mapframe, mMapFragment);
fragmentTransaction.commit();
}
3- Get the map asynchronically:
mMapFragment.getMapAsync(this);
(...)
#Override
public void onMapReady(GoogleMap googleMap) {
//THIS IS JUST EXAMPLE CODE; PUT WHATEVER STUFF YOU NEED HERE
mMap=googleMap;
googleMap.addMarker(new MarkerOptions().position(endLatLng).title(getString(R.string.title)));
mMapFragment.getView().setVisibility(View.GONE);
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(
new LatLng(endLatLng.latitude, endLatLng.longitude), 15);
googleMap.animateCamera(cameraUpdate);
}
This has worked perfectly for me.
I want to display location in map view & map size should be 200X200.
I tried loading map in mapview but its not displaying properly after tapping on direction pointer 2 to 3 times its displaying correct map but not moving.
But when I use complete size of screen for displaying map without changing any code it's loading correctly.How can i display same iin small view?
map code-
static GoogleMap map;
private MapView mapView;
MapsInitializer.initialize(getApplicationContext());
switch (GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext()) )
{
case ConnectionResult.SUCCESS:
//Toast.makeText(getActivity(), "SUCCESS", Toast.LENGTH_SHORT).show();
mapView = (MapView)findViewById(R.id.map);
mapView.onCreate(savedInstanceState);
// Gets to GoogleMap from the MapView and does initialization stuff
if(mapView!=null)
{
map = mapView.getMap();
map.getUiSettings().setMyLocationButtonEnabled(false);
map.setMyLocationEnabled(true);
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(location, 10);
map.animateCamera(cameraUpdate);
map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
}
break;
case ConnectionResult.SERVICE_MISSING:
//Toast.makeText(getActivity(), "SERVICE MISSING", Toast.LENGTH_SHORT).show();
break;
case ConnectionResult.SERVICE_VERSION_UPDATE_REQUIRED:
//Toast.makeText(getActivity(), "UPDATE REQUIRED", Toast.LENGTH_SHORT).show();
break;
default: Toast.makeText(getApplicationContext(), GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext()), Toast.LENGTH_SHORT).show();
}
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(location).zoom(10).bearing(0) // Sets the orientation of the camera to east
.tilt(70) // 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));
Solution -
Done using fragment -
map_screen.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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="200dp"
android:layout_alignParentTop="true"
android:layout_gravity="center_horizontal"
class="com.google.android.gms.maps.SupportMapFragment" />
<TextView
android:id="#+id/reg_office_title"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/mapfragment"
android:layout_gravity="center_horizontal"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="5dp"
android:gravity="center"
android:text="#string/tata_auto"
android:textColor="#color/tatablue"
android:textSize="18sp" />
</RelativeLayout>
java code -
public class MapFragment extends Fragment {
private View view;
public GoogleMap map;
private Location location;
private LatLng mAddress1;
public static boolean inMap=false;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
// TODO Auto-generated method stub
view= inflater.inflate(R.layout.contact_map, container, false);
setMapView();
return view;
}
private void setMapView(){
CurrentLocation mCurrentLoc=new CurrentLocation(getActivity());
location = CurrentLocation.locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
mCurrentLoc.onLocationChanged(location);
} else {
mCurrentLoc.onLocationChanged(location);
}
//class="com.google.android.gms.maps.SupportMapFragment"
map = ((SupportMapFragment)getActivity().getSupportFragmentManager().findFragmentById(R.id.mapfragment)).getMap();
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(mAddress1).zoom(8).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));
}
}
mAddress1 is latitude and longitude of your location.
I tested the code below and there is no problems with the map to the size 200dp x 200dp
Layout:
<?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:background="#FFFFFF"
android:orientation="vertical">
<fragment
android:id="#+id/map"
class="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="200dp"
android:layout_height="200dp" />
</LinearLayout>
Fragment:
public class LocationFragment extends Fragment
{
GoogleMap googleMap;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View v = inflater.inflate(R.layout.fragment_location, container, false);
googleMap = ((SupportMapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
MapsInitializer.initialize(getActivity().getApplicationContext());
googleMap.addMarker(new MarkerOptions()
.position(new LatLng(38.7222524, -9.139336599999979))
.title("MyLocation")
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.ic_mobileedge_navpoint)));
// Move the camera instantly with a zoom of 15.
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom( new LatLng( 38.7222524, -9.139336599999979), 15));
// Zoom in, animating the camera.
googleMap.animateCamera(CameraUpdateFactory.zoomTo(12), 1000, null);
return v;
}
}
Update - 11 August 2020
MapView.getMap() has been replaced with MapView.getMapAsync()
I see that you are using MapView instead of MapFragment. In Google Maps V2, the old MapView class com.google.android.maps.MapView is obsolete. So make sure you use the correct MapView both in your Java code and XML layout which should be
import com.google.android.gms.maps.MapView;
and
<com.google.android.gms.maps.MapView
android:id="#+id/map_view"
android:layout_width="your_width"
android:layout_height="your_height" />
Also make sure you have made all necessary changes in AndroidManifest.xml, which includes defining the API_KEY for Maps V2 as described here.
Apart from this, there is a major thing you have to do if you are using MapView in place of a MapFragment, you have to call the MapView's overridden functions explicitly inside the corresponding overrides of residing Activity just like,
public class YourMapActivity extends Activity {
MapView mMapView;
GoogleMap mMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/* Your OnCreate with Map Initialization */
mMapView = (MapView) findViewById(R.id.map_view);
mMapView.onCreate(Bundle.EMPTY);
mMap = mMapView.getMap();
MapsInitializer.initialize(this);
}
#Override
protected void onResume() {
mMapView.onResume();
super.onResume();
}
#Override
protected void onPause() {
mMapView.onPause();
super.onPause();
}
#Override
protected void onDestroy() {
mMapView.onDestroy();
super.onDestroy();
}
#Override
public void onLowMemory() {
mMapView.onLowMemory();
super.onLowMemory();
}
}
This should be enough for loading a custom sized MapView in your Acitivity. You may also use the following functions to make it suit your requirement.
mMapView.setClickable(false);
mMap.getUiSettings().setMyLocationButtonnabled(false);
mMap.getUiSettings().setZoomControlsEnabled(false);
mMap.getUiSettings().setCompassEnabled(false);
mMap.getUiSettings().setZoomGesturesEnabled(false);
mMap.getUiSettings().setScrollGesturesEnabled(false);
mMap.setMyLocationEnabled(true);