Android Google Map set Style Map with json - android

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.

Related

Android Studio GoogleMaps in Fragment

I want to put the map of Google Maps in my sección with marks and my localitation, but when i put this section, this app closes. And It says ERROR MapFragment.java:83 " LatLng sydney = new LatLng(Float.parseFloat("Lat")".
I put my two code's files:
fragment_map.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<com.google.android.gms.maps.MapView
android:id="#+id/mapView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
MapFragment.java
package com.example.julianrc1.petracecitm;
import android.Manifest;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
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.OnMapReadyCallback;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import java.util.ArrayList;
/**
* A simple {#link Fragment} subclass.
*/
public class MapFragment extends Fragment {
public MapFragment() {
// Required empty public constructor
}
MapView mMapView;
private GoogleMap googleMap;
ArrayList<LatLng> markerPoints;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View rootView = inflater.inflate(R.layout.fragment_map, container, false);
mMapView= (MapView) rootView.findViewById(R.id.mapView);
mMapView.onCreate(savedInstanceState);
mMapView.onResume();
try {
MapsInitializer.initialize(getActivity().getApplicationContext());
} catch (Exception e) {
e.printStackTrace();
}
mMapView.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap mMap) {
googleMap = mMap;
if (checkLocationPermission()) {
if (ContextCompat.checkSelfPermission(getActivity(),
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
//Request location updates:
googleMap.setMyLocationEnabled(true);
}
}
markerPoints = new ArrayList<LatLng>();
googleMap.getUiSettings().setCompassEnabled(true);
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
googleMap.getUiSettings().setRotateGesturesEnabled(true);
// For dropping a marker at a point on the Map
LatLng sydney = new LatLng(Float.parseFloat("Lat"), Float.parseFloat("Long"));
googleMap.addMarker(new MarkerOptions().position(sydney).
title("Title").snippet("TitleName"));
// For zooming automatically to the location of the marker
CameraPosition cameraPosition = new CameraPosition.Builder().target(sydney).zoom(12).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition
(cameraPosition ));
}
});
return rootView;
}
#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();
}
public boolean checkLocationPermission() {
if (ContextCompat.checkSelfPermission(getActivity(),
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
Manifest.permission.ACCESS_FINE_LOCATION)) {
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
new AlertDialog.Builder(getActivity())
.setTitle("")
.setMessage("")
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(getActivity(),new String[]
{Manifest.permission.ACCESS_FINE_LOCATION},1);
}
})
.create()
.show();
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(getActivity(),
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
1);
}
return false;
} else {
return true;
}
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case 1:
{
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the
// location-related task you need to do.
if (ContextCompat.checkSelfPermission(getActivity(),
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
googleMap.setMyLocationEnabled(true);
}
} else {
}
return;
}
}
}
}
Thank you so much for help me!!!
Replace this
LatLng sydney = new LatLng(Float.parseFloat("Lat")
with
LatLng sydney = new LatLng(33.8688,151.2093)

how to use googlemap in fragment android? [duplicate]

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" />

Every time I click on button rangeincrement and rangeDecrement, the application stops. anyone have some solution?

I am trying to write code on button click in a fragment,but the buttons are not working. The buttons are set to increase and decrease the value of textview (rangeText).
I have implemented OnClickListener to my fragment.
I want to know where is the mistake.
package com.neoresearch.bookmyspace;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
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.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
/**
* A fragment that launches other parts of the demo application.
*/
public class ParkingFinderMapFragment extends Fragment implements View.OnClickListener {
LinearLayout layoutOfPopup;
PopupWindow popupMessage;
Button popupButton, insidePopupButton, searchButton, rangeIncrement, rangeDecrement;
TextView rangeText;
TextView name, contact, address, availability;
AutoCompleteTextView searchText;
LatLng latLng;
MarkerOptions markerOptions;
MapView mMapView;
GoogleMap googleMap;
private EditText editText;
String string;
private View v;
int range;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
}
#Override
public void onDetach() {
super.onDetach();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// inflat and return the layout
v = inflater.inflate(R.layout.fragment_parking_finder_map, container,
false);
searchText = (AutoCompleteTextView) v.findViewById(R.id.search_on_map);
searchButton = (Button) v.findViewById(R.id.button_search);
rangeIncrement = (Button) v.findViewById(R.id.range_increment);
rangeDecrement = (Button) v.findViewById(R.id.range_decrament);
rangeText = (TextView) v.findViewById(R.id.range_select);
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);
LatLng indore = new LatLng(22.7000, 75.9000);
final MarkerOptions marker2 = new MarkerOptions().position(indore).title("Indore");
googleMap.addMarker(marker2);
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(22.7000, 75.9000)).zoom(8).build();
googleMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
// Perform any camera updates here
googleMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
PopupOnMap pop = new PopupOnMap(getActivity());
pop.show();
pop.setName("prafull", marker.getTitle(), "8269564260");
return false;
}
});
searchButton.setOnClickListener(this);
rangeDecrement.setOnClickListener(this);//these are my buttons
rangeIncrement.setOnClickListener(this);
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();
}
//here is onclick listeners
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button_search:
break;
case R.id.range_increment:
range = Integer.parseInt(rangeText.getText().toString());
if (range > 0 && range < 20) {
range = range++;
}
rangeText.setText(range);
break;
case R.id.range_decrament:
range = Integer.parseInt(rangeText.getText().toString());
if (range > 0 && range < 20) {
range = range--;
}
rangeText.setText(range);
break;
}
}
}
Make the following changes to your onClick() method :
case R.id.range_increment:
range = Integer.parseInt(rangeText.getText().toString());
if (range > 0 && range < 20) {
range = range++;
}
rangeText.setText(String.valueOf(range));
break;
case R.id.range_decrament:
range = Integer.parseInt(rangeText.getText().toString());
if (range > 0 && range < 20) {
range = range--;
}
rangeText.setText(String.valueOf(range));
break;

Display a path in my maps android app

I tried to develop a android app with maps. I'm a beginner in android app development, i doesn't know how to generate a path between my current position and to the destination. I can able to view by current location by the code shown below.
package com.example.myapp;
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.model.LatLng;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class Grandinmaps extends Activity implements OnMapReadyCallback{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_grandinmaps);
MapFragment mapFragment = (MapFragment) getFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap map) {
// TODO Auto-generated method stub
map.setMyLocationEnabled(true);
map.moveCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(12.971907, 80.220462), 18));
}
}
And i doesn't know the code to generate the path to destination.
Any HELP...!!! Please:-)
For Drawing Route you can use this code:
Call for printing location route:
GmapV2Direction route;
Document document;
LatLng toPosition = new LatLng(routeData.get(i).latitude, routeData.get(i).longitude);
new GetRouteTask() {
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
}.execute((LatLng) toPosition);
private class GetRouteTask extends AsyncTask<LatLng, Void, String> {
String response = "";
#Override
protected String doInBackground(LatLng... params) {
document = route.getDocument(fromPosition, params[0], GmapV2Direction.MODE_WALKING);//fromPosition is another LatLng object.can be your current location.
response = "Success";
return response;
}
#Override
protected void onPostExecute(String s) {
// directionMap.clear();
if (response.equalsIgnoreCase("Success")) {
Log.v("Map", "got here");
ArrayList<LatLng> directionPoint = route.getDirection(document);
PolylineOptions rectLine = new PolylineOptions().width(10).color(
Color.RED);
for (int i = 0; i < directionPoint.size(); i++) {
rectLine.add(directionPoint.get(i));
}
// Adding route on the map
map.addPolyline(rectLine);
}
}
}

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"));
}
}

Categories

Resources