I want to show multiple marks on google map v2 on run time.I have location table on remote server which contain all latitude and longitude.
I want to read latitude and longitude to show marker against each entry in location table but I don't know It give place one marker on google map.....First values in case of list and If use hashMap then give last value in database
Here is my code that am using to read and show marker on google map.Please help m and thanks in advance
public class MapActivity extends AppCompatActivity {
private GoogleMap mMap; // Might be null if Google Play services APK is not available.
JSONArray jsonArray;
ArrayList<HashMap<String, String>> prodArrayList = new ArrayList<HashMap<String, String>>();
HashMap<String, String> HashMap ;
String text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
setUpMapIfNeeded();
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
/**
* Sets up the map if it is possible to do so (i.e., the Google Play services APK is correctly
* installed) and the map has not already been instantiated.. This will ensure that we only ever
* call {#link #setUpMap()} once when {#link #mMap} is not null.
* <p/>
* If it isn't installed {#link SupportMapFragment} (and
* {#link com.google.android.gms.maps.MapView MapView}) will show a prompt for the user to
* install/update the Google Play services APK on their device.
* <p/>
* A user can return to this FragmentActivity after following the prompt and correctly
* installing/updating/enabling the Google Play services. Since the FragmentActivity may not
* have been completely destroyed during this process (it is likely that it would only be
* stopped or paused), {#link #onCreate(Bundle)} may not be called again so we should call this
* method in {#link #onResume()} to guarantee that it will be called.
*/
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();
CameraPosition cameraPosition = new CameraPosition.Builder().target(
new LatLng(32.634723, 74.1601851)).zoom(12).build();
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
ActionStartsHere();
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap();
}
}
}
/**
* 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.
* <p/>
* This should only be called once and when we are sure that {#link #mMap} is not null.
*/
private void setUpMap() {
ReadDriverLocation task1 = new ReadDriverLocation();
task1.execute(new String[]{"http://ahsan.comyr.com/ReadLocation.php"});
}
//This method call thread ofter 10 second
public void ActionStartsHere() {
CallBangroundClass();
}
public void CallBangroundClass() {
new CountDownTimer(11000, 30000) {
#Override
public void onTick(long millisUntilFinished) {
//Object of ReadActiveDriver Class extends with AsyncTask Class
}
#Override
public void onFinish() {
ActionStartsHere();
}
}.start();
}
///////////////////////////////////////////////////////////////////////////
private class ReadDriverLocation extends AsyncTask<String,Void,Boolean>
{
String text = "";
ArrayList<String> list;
ArrayList<String> list1;
ArrayList<String> list2;
#Override
protected Boolean doInBackground(String... urls) {
InputStream inputStream;
for(String url1: urls) {
try {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url1);
HttpResponse response = client.execute(post);
inputStream = response.getEntity().getContent();
} catch (IOException e) {
Toast.makeText(MapActivity.this, e.toString(), Toast.LENGTH_LONG).show();
return false;
}
BufferedReader reader;
try {
reader = new BufferedReader(new InputStreamReader(inputStream));
String line = null;
while((line = reader.readLine())!=null)
{
text += line +"\n";
}
} catch (IOException e) {
e.printStackTrace();
}
list = new ArrayList<String>();
list1 = new ArrayList<String>();
list2 = new ArrayList<String>();
HashMap = new HashMap<String, String>();
try {
jsonArray = new JSONArray(text);
for(int i=0; i<jsonArray.length(); i++)
{
JSONObject jsonObject = jsonArray.getJSONObject(i);
String lati = jsonObject.getString("latitude");
String longLat = jsonObject.getString("longitude");
String Time = jsonObject.getString("time");
list.add(lati);
list1.add(longLat);
list2.add(Time);
//HashMap.put("Latitude", lati);
//HashMap.put("Longitude", longLat);
//HashMap.put("time", Time);
//prodArrayList.add(HashMap);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
return true;
}
#Override
protected void onPostExecute(Boolean result) {
if(result == true)
{
for(int i=0; i<list.size(); i++)
{
Double latitude = Double.parseDouble(list.get(i));
Double longitude = Double.parseDouble(list1.get(i));
MarkerOptions marker = new MarkerOptions().position(new LatLng(latitude,longitude)).title(list2.get(i));
// GREEN color icon
mMap.addMarker(marker);
}
/*
for(int i=0; i<prodArrayList.size(); i++)
{
HashMap<String,String> hMap = prodArrayList.get(i);
Double latitude = Double.parseDouble(hMap.get("Latitude"));
Double longitude = Double.parseDouble(hMap.get("Longitude"));
MarkerOptions marker = new MarkerOptions().position(new LatLng(latitude,longitude)).title(hMap.get("time"));
// GREEN color icon
mMap.addMarker(marker);
}*/
}
else
{
Toast.makeText(MapActivity.this, "Error in Loading...",Toast.LENGTH_LONG).show();
}
}
}
}
When you use HashMap then you are getting last value because you are using same HashMap object in your for loop. According to HashMap definition,if you use same key then prior value for the key is dropped and replaced with the new one.
HashMap = new HashMap();// This hashMap is used entire for loop
try {
jsonArray = new JSONArray(text);
for(int i=0; i<jsonArray.length(); i++)
{
JSONObject jsonObject = jsonArray.getJSONObject(i);
String lati = jsonObject.getString("latitude");
String longLat = jsonObject.getString("longitude");
String Time = jsonObject.getString("time");
// You use here duplicate key hence last value retained by hash map
HashMap.put("Latitude", lati);
HashMap.put("Longitude", longLat);
HashMap.put("time", Time);
prodArrayList.add(HashMap);
}
} catch (JSONException e) {
e.printStackTrace();
}
In order to get right value from hashMap then create new instance for hashmap in for loop as follows :
try {
jsonArray = new JSONArray(text);
for(int i=0; i<jsonArray.length(); i++)
{
JSONObject jsonObject = jsonArray.getJSONObject(i);
String lati = jsonObject.getString("latitude");
String longLat = jsonObject.getString("longitude");
String Time = jsonObject.getString("time");
HashMap = new HashMap<String, String>();
HashMap.put("Latitude", lati);
HashMap.put("Longitude", longLat);
HashMap.put("time", Time);
prodArrayList.add(HashMap);
}
} catch (JSONException e) {
e.printStackTrace();
}
Set your marker as follows :
for(int i=0; i<prodArrayList.size(); i++)
{
HashMap<String,String> hMap = prodArrayList.get(i);
Double latitude = Double.parseDouble(hMap.get("Latitude"));
Double longitude = Double.parseDouble(hMap.get("Longitude"));
MarkerOptions marker = new MarkerOptions().position(new LatLng(latitude,longitude)).title(hMap.get("time"));
// GREEN color icon
mMap.addMarker(marker);
}
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I have to draw a route between two addresses which are written in two place autocomplete fragments. I searched for it but most code are of onclick event. I have to draw polyline based on the address written in the fragments. Can you give me a general idea on how to write a code for this?
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
Context context;
Polyline polyline;
Marker markers;
#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);
PlaceAutocompleteFragment autocompleteFragment = (PlaceAutocompleteFragment)
getFragmentManager().findFragmentById(R.id.place_autocomplete_fragment);
autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
#Override
public void onPlaceSelected(Place place) {
// TODO: Get info about the selected place.
addMarker(place);
// Log.i(TAG, "Place: " + place.getName());
String placeName = place.getName().toString();
}
#Override
public void onError(Status status) {
// TODO: Handle the error.
//Log.i(TAG, "An error occurred: " + status);
}
});
final PlaceAutocompleteFragment autocompleteFragments = (PlaceAutocompleteFragment)
getFragmentManager().findFragmentById(R.id.place_autocomplete_fragments);
autocompleteFragments.setOnPlaceSelectedListener(new PlaceSelectionListener() {
#Override
public void onPlaceSelected(Place place) {
// TODO: Get info about the selected place.
addMarker(place);
// Log.i(TAG, "Place: " + place.getName());
String placeName = place.getName().toString();
}
#Override
public void onError(Status status) {
// TODO: Handle the error.
//Log.i(TAG, "An error occurred: " + status);
}
});
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
#Override
public void onMapReady(final GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Sydney and move the camera
//LatLng warora = new LatLng(20.2407, 79.0136);
//LatLng amravati=new LatLng(20.9374,77.7796);
/*LatLng nagpur=new LatLng(21.1458,79.0882);
PolylineOptions polylineOptions=new PolylineOptions().add(warora).add(nagpur).width(5).color(Color.BLUE)
.geodesic(true);
googleMap.addPolyline(polylineOptions);
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(warora,8));
mMap.addMarker(new MarkerOptions().position(warora).title("Marker in India"));
//mMap.addMarker(new MarkerOptions().position(amravati).title("Marker in Pune"));
mMap.addMarker(new MarkerOptions().position(nagpur).title("Marker in Nagpur"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(warora));
*/
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
mMap.setMyLocationEnabled(true);
}
public void addMarker(Place p) {
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(p.getLatLng()).title(p.getName() + "");
mMap.addMarker(markerOptions);
mMap.moveCamera(CameraUpdateFactory.newLatLng(p.getLatLng()));
mMap.animateCamera(CameraUpdateFactory.zoomTo(9));
}
}
In my code, I have added the marker but both the search box are calling one method(addMarker). I guess that's the reason i can't get the polyline between them. I tried make to different method with same code and then add polyline but it did not work.
I'm giving you code for drawing path plus getting driving distance and travel time.
Create a new java file namely “DirectionsJSONParser.java”:
public class DirectionsJSONParser {
/** Receives a JSONObject and returns a list of lists containing
latitude and longitude */
public List<List<HashMap<String,String>>> parse(JSONObject jObject){
List<List<HashMap<String, String>>> routes = new
ArrayList<List<HashMap<String,String>>>() ;
JSONArray jRoutes = null;
JSONArray jLegs = null;
JSONArray jSteps = null;
JSONObject jDistance = null;
JSONObject jDuration = null;
try {
jRoutes = jObject.getJSONArray("routes");
/** Traversing all routes */
for(int i=0;i<jRoutes.length();i++){
jLegs = ( (JSONObject)jRoutes.get(i)).getJSONArray("legs");
List<HashMap<String, String>> path = new
ArrayList<HashMap<String, String>>();
/** Traversing all legs */
for(int j=0;j<jLegs.length();j++){
/** Getting distance from the json data */
jDistance = ((JSONObject)
jLegs.get(j)).getJSONObject("distance");
HashMap<String, String> hmDistance = new HashMap<String,
String>();
hmDistance.put("distance", jDistance.getString("text"));
/** Getting duration from the json data */
jDuration = ((JSONObject)
jLegs.get(j)).getJSONObject("duration");
HashMap<String, String> hmDuration = new HashMap<String,
String>();
hmDuration.put("duration", jDuration.getString("text"));
/** Adding distance object to the path */
path.add(hmDistance);
/** Adding duration object to the path */
path.add(hmDuration);
jSteps = (
(JSONObject)jLegs.get(j)).getJSONArray("steps");
/** Traversing all steps */
for(int k=0;k<jSteps.length();k++){
String polyline = "";
polyline = (String)((JSONObject)
((JSONObject)jSteps.get(k)).get("polyline"))
.get("points");
List<LatLng> list = decodePoly(polyline);
/** Traversing all points */
for(int l=0;l<list.size();l++){
HashMap<String, String> hm = new HashMap<String,
String>();
hm.put("lat",
Double.toString(((LatLng)list.get(l))
.latitude) );
hm.put("lng",
Double.toString(((LatLng)list.get(l))
.longitude) );
path.add(hm);
}
}
}
routes.add(path);
}
} catch (JSONException e) {
e.printStackTrace();
}catch (Exception e){
}
return routes;
}
/**
* Method to decode polyline points
* Courtesy : jeffreysambells.com/2010/05/27/decoding-polylines-from-
google-maps-direction-api-with-java
* */
private List<LatLng> decodePoly(String encoded) {
List<LatLng> poly = new ArrayList<LatLng>();
int index = 0, len = encoded.length();
int lat = 0, lng = 0;
while (index < len) {
int b, shift = 0, result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lat += dlat;
shift = 0;
result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lng += dlng;
LatLng p = new LatLng((((double) lat / 1E5)),
(((double) lng / 1E5)));
poly.add(p);
}
return poly;
}
}
Now in MainActivity where your map exists:
public class MainActivity extends FragmentActivity {
GoogleMap map;
ArrayList<LatLng> markerPoints;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initializing
markerPoints = new ArrayList<LatLng>();
// Getting reference to SupportMapFragment of the activity_main
SupportMapFragment fm =
(SupportMapFragment)getSupportFragmentManager().
findFragmentById(R.id.map);
// Getting Map for the SupportMapFragment
map = fm.getMap();
// Enable MyLocation Button in the Map
map.setMyLocationEnabled(true);
// Setting onclick event listener for the map
map.setOnMapClickListener(new OnMapClickListener() {
#Override
public void onMapClick(LatLng point) {
// Already two locations
if(markerPoints.size()>1){
markerPoints.clear();
map.clear();
}
// Adding new item to the ArrayList
markerPoints.add(point);
// Creating MarkerOptions
MarkerOptions options = new MarkerOptions();
// Setting the position of the marker
options.position(point);
/**
* For the start location, the color of marker is GREEN and
* for the end location, the color of marker is RED.
*/
if(markerPoints.size()==1){
options.icon(BitmapDescriptorFactory.
defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
}else if(markerPoints.size()==2){
options.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_RED));
}
// Add new marker to the Google Map Android API V2
map.addMarker(options);
// Checks, whether start and end locations are captured
if(markerPoints.size() >= 2){
LatLng origin = markerPoints.get(0);
LatLng dest = markerPoints.get(1);
// Getting URL to the Google Directions API
String url = getDirectionsUrl(origin, dest);
DownloadTask downloadTask = new DownloadTask();
// Start downloading json data from Google Directions
API
downloadTask.execute(url);
}
}
});
}
private String getDirectionsUrl(LatLng origin,LatLng dest){
// Origin of route
String str_origin = "origin="+origin.latitude+","+origin.longitude;
// Destination of route
String str_dest = "destination="+dest.latitude+","+dest.longitude;
// Sensor enabled
String sensor = "sensor=false";
// Building the parameters to the web service
String parameters = str_origin+"&"+str_dest+"&"+sensor;
// Output format
String output = "json";
// Building the url to the web service
String url =
"https://maps.googleapis.com/maps/api/directions/"+output+"?"
+parameters;
return url;
}
/** A method to download json data from url */
private String downloadUrl(String strUrl) throws IOException{
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try{
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new
InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while( ( line = br.readLine()) != null){
sb.append(line);
}
data = sb.toString();
br.close();
}catch(Exception e){
Log.d("Exception while downloading url", e.toString());
}finally{
iStream.close();
urlConnection.disconnect();
}
return data;
}
// Fetches data from url passed
private class DownloadTask extends AsyncTask<String, Void, String>{
// Downloading data in non-ui thread
#Override
protected String doInBackground(String... url) {
// For storing data from web service
String data = "";
try{
// Fetching the data from web service
data = downloadUrl(url[0]);
}catch(Exception e){
Log.d("Background Task",e.toString());
}
return data;
}
// Executes in UI thread, after the execution of
// doInBackground()
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
ParserTask parserTask = new ParserTask();
// Invokes the thread for parsing the JSON data
parserTask.execute(result);
}
}
/** A class to parse the Google Places in JSON format */
private class ParserTask extends AsyncTask<String, Integer,
List<List<HashMap<String,String>>> >{
// Parsing the data in non-ui thread
#Override
protected List<List<HashMap<String, String>>>
doInBackground(String...
jsonData) {
JSONObject jObject;
List<List<HashMap<String, String>>> routes = null;
try{
jObject = new JSONObject(jsonData[0]);
DirectionsJSONParser parser = new DirectionsJSONParser();
// Starts parsing data
routes = parser.parse(jObject);
}catch(Exception e){
e.printStackTrace();
}
return routes;
}
// Executes in UI thread, after the parsing process
#Override
protected void onPostExecute(List<List<HashMap<String,
String>>> result) {
ArrayList<LatLng> points = null;
PolylineOptions lineOptions = null;
MarkerOptions markerOptions = new MarkerOptions();
String distance = "";
String duration = "";
if(result.size()<1){
Toast.makeText(getBaseContext(), "No Points",
Toast.LENGTH_SHORT).show();
return;
}
// Traversing through all the routes
for(int i=0;i<result.size();i++){
points = new ArrayList<LatLng>();
lineOptions = new PolylineOptions();
// Fetching i-th route
List<HashMap<String, String>> path = result.get(i);
// Fetching all the points in i-th route
for(int j=0;j<path.size();j++){
HashMap<String,String> point = path.get(j);
if(j==0){ // Get distance from the list
distance = (String)point.get("distance");
continue;
}else if(j==1){ // Get duration from the list
duration = (String)point.get("duration");
continue;
}
double lat = Double.parseDouble(point.get("lat"));
double lng = Double.parseDouble(point.get("lng"));
LatLng position = new LatLng(lat, lng);
points.add(position);
}
// Adding all the points in the route to LineOptions
lineOptions.addAll(points);
lineOptions.width(2);
lineOptions.color(Color.RED);
}
// Drawing polyline in the Google Map for the i-th route
map.addPolyline(lineOptions);
}
}
#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;
}
}
That's it!
Here is the link if you need more explanation.
You need to get the coordinates of your two addresses - Google Maps has an API library that does this. Then follow the guide to draw a polyline on your map at this link. Follow the guides at both links and you should be sorted. Hope this helps.
Use google directions API to get the waypoints between your 2 addresses.There is a Util lib by Google to help you show the "overview_polyline" from the response on the map.
I'm having a question about how to do a project that I thought would be simple.
Next I have an app that sends the location of the mobile phone by 10 seconds to MySql, so alright.
But I just need to now display in another app the current location these users on the mapped 10 seconds without having to open and close the Activity.
In this code below the mapping of the markers that come from the Mysql bank using json is displayed. Any tips?
public class MainActivity extends FragmentActivity {
// Google Map
private GoogleMap googleMap;
// Latitude & Longitude
private Double Latitude = 0.00;
private Double Longitude = 0.00;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//*** Permission StrictMode
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
ArrayList<HashMap<String, String>> location = null;
String url = "http://192.168.1.202/android/getLatLon.php";
try {
JSONArray data = new JSONArray(getHttpGet(url));
location = new ArrayList<HashMap<String, String>>();
HashMap<String, String> map;
for(int i = 0; i < data.length(); i++){
JSONObject c = data.getJSONObject(i);
map = new HashMap<String, String>();
map.put("LocationID", c.getString("LocationID"));
map.put("Latitude", c.getString("Latitude"));
map.put("Longitude", c.getString("Longitude"));
map.put("LocationName", c.getString("LocationName"));
location.add(map);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// *** Display Google Map
googleMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.googleMap)).getMap();
// *** Focus & Zoom
Latitude = Double.parseDouble(location.get(0).get("Latitude").toString());
Longitude = Double.parseDouble(location.get(0).get("Longitude").toString());
LatLng coordinate = new LatLng(Latitude, Longitude);
googleMap.setMapType(com.google.android.gms.maps.GoogleMap.MAP_TYPE_HYBRID);
googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(coordinate, 17));
// *** Marker (Loop)
for (int i = 0; i < location.size(); i++) {
Latitude = Double.parseDouble(location.get(i).get("Latitude").toString());
Longitude = Double.parseDouble(location.get(i).get("Longitude").toString());
String name = location.get(i).get("LocationName").toString();
MarkerOptions marker = new MarkerOptions().position(new LatLng(Latitude, Longitude)).title(name);
googleMap.addMarker(marker);
}
}
public static String getHttpGet(String url) {
StringBuilder str = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) { // Download OK
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
str.append(line);
}
} else {
Log.e("Log", "Failed to download result..");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return str.toString();
}
}
You can use COUNTDOWN TIMER, COUNT DOWN TIMER EXAMPLE so that every 10 sec it makes network request and you will get response with the updated value.
and you can update your marker with the new LATITUDE, LONGITUDE value. And keep in mind add marker only on the first network request after
that don't need to add marker only you need to change your marker position. .how to change marker position
But i will recommend you its not a good idea to make network request every time(Every 10 sec). it may be possible that user is not changing there location since one hour.so its worthless API call. so it would be better if you use REAL TIME DATABASE(like Firebase real time db). and listen your data change whenever your db value will be updated it will notify you. Firebase Real time DB Doc reference
If you want to update your map on some interval of time without having to open and close thee activity. You should move your logic from onCreate() method.
Thread myLoopingThread = new Thread(new Runnable() {
#Override
public void run() {
while(!Thread.currentThread().isInterrupted()){
final String result = getHttpGet("http://192.168.1.202/android/getLatLon.php");
runOnUiThread(new Runnable() {
#Override
public void run() {
UpdateMap(result);
}
});
Thread.sleep(timeToSleep);
}
}
});
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//do other stuff..
myLoopingThread.start();
}
//also we should stop the thread when its not needed anymore
#Override
protected void onDestroy(){
myLoopingThread.interrupt();
super.onDestroy();
}
void UpdateMap(String input){
ArrayList<HashMap<String, String>> location = null;
try {
JSONArray data = new JSONArray(input);
location = new ArrayList<HashMap<String, String>>();
HashMap<String, String> map;
for(int i = 0; i < data.length(); i++){
JSONObject c = data.getJSONObject(i);
map = new HashMap<String, String>();
map.put("LocationID", c.getString("LocationID"));
map.put("Latitude", c.getString("Latitude"));
map.put("Longitude", c.getString("Longitude"));
map.put("LocationName", c.getString("LocationName"));
location.add(map);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// *** Display Google Map
googleMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.googleMap)).getMap();
// *** Focus & Zoom
Latitude = Double.parseDouble(location.get(0).get("Latitude").toString());
Longitude = Double.parseDouble(location.get(0).get("Longitude").toString());
LatLng coordinate = new LatLng(Latitude, Longitude);
googleMap.setMapType(com.google.android.gms.maps.GoogleMap.MAP_TYPE_HYBRID);
googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(coordinate, 17));
// *** Marker (Loop)
for (int i = 0; i < location.size(); i++) {
Latitude = Double.parseDouble(location.get(i).get("Latitude").toString());
Longitude = Double.parseDouble(location.get(i).get("Longitude").toString());
String name = location.get(i).get("LocationName").toString();
MarkerOptions marker = new MarkerOptions().position(new LatLng(Latitude, Longitude)).title(name);
googleMap.addMarker(marker);
}
}
I am trying to display locations of places I got using the google maps places api. But the markers of my search results are not showing up on the map. And I can't seem to find the problem. Below is a copy of my source code with my logcat log. Any help will be really appreciated. Thank you in advance :) .
My MainActivity
public class MainActivity extends FragmentActivity implements LocationListener, GoogleMap.OnMapClickListener {
GoogleMap mGoogleMap;
Spinner mSprPlaceType;
String[] mPlaceType=null;
String[] mPlaceTypeName=null;
double mLatitude=0;
double mLongitude=0;
LatLng center;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Array of place types
mPlaceType = getResources().getStringArray(R.array.place_type);
// Array of place type names
mPlaceTypeName = getResources().getStringArray(R.array.place_type_name);
// Creating an array adapter with an array of Place types
// to populate the spinner
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, mPlaceTypeName);
// Getting reference to the Spinner
mSprPlaceType = (Spinner) findViewById(R.id.spr_place_type);
// Setting adapter on Spinner to set place types
mSprPlaceType.setAdapter(adapter);
Button btnFind;
// Getting reference to Find Button
btnFind = ( Button ) findViewById(R.id.btn_find);
// Getting Google Play availability status
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());
if(status!=ConnectionResult.SUCCESS){ // Google Play Services are not available
int requestCode = 10;
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
dialog.show();
}else { // Google Play Services are available
// Getting reference to the SupportMapFragment
SupportMapFragment fragment = ( SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map);
// Getting Google Map
mGoogleMap = fragment.getMap();
mGoogleMap.setOnMapClickListener(this);
mGoogleMap.getUiSettings().isCompassEnabled();
mGoogleMap.getUiSettings().setZoomControlsEnabled(true);
mGoogleMap.getUiSettings().setScrollGesturesEnabled(true);
mGoogleMap.getUiSettings().setMapToolbarEnabled(true);
mGoogleMap.setMyLocationEnabled(true);
// Enabling MyLocation in Google Map
mGoogleMap.setMyLocationEnabled(true);
// Getting LocationManager object from System Service LOCATION_SERVICE
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// Creating a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Getting the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
// Getting Current Location From GPS
Location location = locationManager.getLastKnownLocation(provider);
if(location!=null){
onLocationChanged(location);
}
locationManager.requestLocationUpdates(provider, 20000, 0, this);
// Setting click event lister for the find button
btnFind.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
int selectedPosition = mSprPlaceType.getSelectedItemPosition();
String type = mPlaceType[selectedPosition];
StringBuilder sb = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
sb.append("location="+mLatitude+","+mLongitude);
sb.append("&radius=5000");
sb.append("&types="+type);
sb.append("&sensor=true");
sb.append("&key=MY_API_KEY");
// Creating a new non-ui thread task to download Google place json data
PlacesTask placesTask = new PlacesTask();
// Invokes the "doInBackground()" method of the class PlaceTask
Log.d("url",sb.toString());
placesTask.execute(sb.toString());
}
});
}
}
/** A method to download json data from url */
private String downloadUrl(String strUrl) throws IOException{
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try{
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while( ( line = br.readLine()) != null){
sb.append(line);
}
data = sb.toString();
br.close();
}catch(Exception e){
Log.d("Exception while downloading url", e.toString());
}finally{
iStream.close();
urlConnection.disconnect();
}
return data;
}
#Override
public void onMapClick(LatLng latLng) {
center = mGoogleMap.getCameraPosition().target;
// Toast.makeText(MainActivity.this, center.toString(), Toast.LENGTH_LONG).show();
mLatitude= center.latitude;
mLongitude=center.longitude;
}
/** A class, to download Google Places */
private class PlacesTask extends AsyncTask<String, Integer, String>{
String data = null;
// Invoked by execute() method of this object
#Override
protected String doInBackground(String... url) {
try{
data = downloadUrl(url[0]);
}catch(Exception e){
Log.d("Background Task",e.toString());
}
return data;
}
// Executed after the complete execution of doInBackground() method
#Override
protected void onPostExecute(String result){
ParserTask parserTask = new ParserTask();
// Start parsing the Google places in JSON format
// Invokes the "doInBackground()" method of the class ParseTask
parserTask.execute(result);
}
}
/** A class to parse the Google Places in JSON format */
private class ParserTask extends AsyncTask<String, Integer, List<HashMap<String,String>>>{
JSONObject jObject;
// Invoked by execute() method of this object
#Override
protected List<HashMap<String,String>> doInBackground(String... jsonData) {
List<HashMap<String, String>> places = null;
PlaceJSONParser placeJsonParser = new PlaceJSONParser();
try{
jObject = new JSONObject(jsonData[0]);
/** Getting the parsed data as a List construct */
places = placeJsonParser.parse(jObject);
}catch(Exception e){
Log.d("Exception",e.toString());
}
return places;
}
// Executed after the complete execution of doInBackground() method
#Override
protected void onPostExecute(List<HashMap<String,String>> list){
// Clears all the existing markers
mGoogleMap.clear();
for(int i=0;i<list.size();i++){
// Creating a marker
MarkerOptions markerOptions = new MarkerOptions();
// Getting a place from the places list
HashMap<String, String> hmPlace = list.get(i);
// Getting latitude of the place
double lat = Double.parseDouble(hmPlace.get("lat"));
// Getting longitude of the place
double lng = Double.parseDouble(hmPlace.get("lng"));
// Getting name
String name = hmPlace.get("place_name");
// Getting vicinity
String vicinity = hmPlace.get("vicinity");
LatLng latLng = new LatLng(lat, lng);
// Setting the position for the marker
markerOptions.position(latLng);
// Setting the title for the marker.
//This will be displayed on taping the marker
markerOptions.title(name + " : " + vicinity);
// Placing a marker on the touched position
mGoogleMap.addMarker(markerOptions);
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu_main; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public void onLocationChanged(Location location) {
mLatitude = location.getLatitude();
mLongitude = location.getLongitude();
LatLng latLng = new LatLng(mLatitude, mLongitude);
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(12));
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
My JSONParser :
public class JSONParser {
/** Receives a JSONObject and returns a list */
public List<HashMap<String,String>> parse(JSONObject jObject){
JSONArray jPlaces = null;
try {
/** Retrieves all the elements in the 'places' array */
jPlaces = jObject.getJSONArray("results");
} catch (JSONException e) {
e.printStackTrace();
}
/** Invoking getPlaces with the array of json object
* where each json object represent a place
*/
return getPlaces(jPlaces);
}
private List<HashMap<String, String>> getPlaces(JSONArray jPlaces){
int placesCount = jPlaces.length();
List<HashMap<String, String>> placesList = new ArrayList<HashMap<String,String>>();
HashMap<String, String> place = null;
/** Taking each place, parses and adds to list object */
for(int i=0; i<placesCount;i++){
try {
/** Call getPlace with place JSON object to parse the place */
place = getPlace((JSONObject)jPlaces.get(i));
placesList.add(place);
} catch (JSONException e) {
e.printStackTrace();
}
}
return placesList;
}
/** Parsing the Place JSON object */
private HashMap<String, String> getPlace(JSONObject jPlace){
HashMap<String, String> place = new HashMap<String, String>();
String placeName = "-NA-";
String vicinity="-NA-";
String latitude="";
String longitude="";
try {
// Extracting Place name, if available
if(!jPlace.isNull("name")){
placeName = jPlace.getString("name");
}
// Extracting Place Vicinity, if available
if(!jPlace.isNull("vicinity")){
vicinity = jPlace.getString("vicinity");
}
latitude = jPlace.getJSONObject("geometry").getJSONObject("location").getString("lat");
longitude = jPlace.getJSONObject("geometry").getJSONObject("location").getString("lng");
place.put("place_name", placeName);
place.put("vicinity", vicinity);
place.put("lat", latitude);
place.put("lng", longitude);
} catch (JSONException e) {
e.printStackTrace();
}
return place;
}}
My activity_main:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
tools:context=".MainActivity">
<Spinner
android:id="#+id/spr_place_type"
android:layout_width="200dp"
android:layout_height="60dp"
android:gravity="center"
/>
<Button
android:id="#+id/btn_find"
android:layout_width="200dp"
android:layout_height="60dp"
android:layout_alignParentTop="true"
android:layout_toRightOf="#id/spr_place_type"
android:text="#string/str_btn_find" />
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/map"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/spr_place_type"
class="com.google.android.gms.maps.SupportMapFragment" />
<ImageView
android:layout_width="30dp"
android:layout_height="50dp"
android:id="#+id/imageView"
android:src="#drawable/location"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
And my logcat:
private void getParticularTypeLocation(String selType){
StringBuilder googlePlacesUrl = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
googlePlacesUrl.append("location=" + latitude + "," + longitude);
googlePlacesUrl.append("&radius=" + 5000);
googlePlacesUrl.append("&types=" + selType);
googlePlacesUrl.append("&sensor=true");
googlePlacesUrl.append("&key=" + GOOGLE_API_KEY);
GooglePlacesReadTask googlePlacesReadTask = new GooglePlacesReadTask();
Object[] toPass = new Object[2];
toPass[0] = googlePlacesUrl.toString();
toPass[1] = BitmapDescriptorFactory.HUE_VIOLET;
googlePlacesReadTask.execute(toPass);
MarkerOptions marker = new MarkerOptions().position(
new LatLng(randomLocation[0], randomLocation[1]))
.title("Current Location");
marker.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
googleMap.addMarker(marker);
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(randomLocation[0],
randomLocation[1])).zoom(13).build();
googleMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
}
You may refer this code this will get the relavent places in google map.
Give string input as type like hospital,hotel,policestation,park etc.,
I hope,this may help you.
I'm trying to implement an simple navigation app using Google maps. Initially I developed a code for marking two Geo points on map and showing route between them.
Now I am trying to move the first marker towards second marker (destination) based on users location.
For this I used LocationListener and implemented code in onLocationChanged.
The problem is onLocationChanged is not getting fired and marker is not moving based on user location.
Here is my code.
MapActivity.java
public class MapActivity extends FragmentActivity implements OnMapClickListener, LocationListener{
private GoogleMap gMap;
private ArrayList<LatLng> markersArray; //Marker points ArrayList
private ArrayList<Marker> markers;
private MarkerOptions options; //Marker options
String distance="";
String duration="";
private TextView travelDetails;
private ProgressDialog pDialog;
private double lattitude=0.0;
private double longitude=0.0;
Marker mMarker;
String bestAvailableProvider;
private LocationManager mLocationManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
//Loading Google Maps
try{
loadMapView();
markersArray=new ArrayList<LatLng>();
markers=new ArrayList<Marker>();
gMap.setOnMapClickListener(this);
gMap.setMyLocationEnabled(true);
gMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
travelDetails=(TextView) findViewById(R.id.lbl_traveldetails);
pDialog=new ProgressDialog(MapActivity.this);
}catch(Exception e){
e.printStackTrace();
}
}
/*
* This method loads map
*
*/
private void loadMapView(){
if (gMap==null) {
gMap=((SupportMapFragment)getSupportFragmentManager()
.findFragmentById(R.id.map_fragment)).getMap();
}
mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
// Specify Location Provider criteria
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setSpeedRequired(false);
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,this);
}
/*
* catches onclick event of map
* #see com.google.android.gms.maps.GoogleMap.OnMapClickListener#onMapClick(com.google.android.gms.maps.model.LatLng)
*/
#Override
public void onMapClick(LatLng point) {
//Clearing markers in map
if (markersArray.size()>1) {
markersArray.clear();
gMap.clear();
}
//Adding marker to array
markersArray.add(point);
//marking point on Map
addMarkerOnMap(point);
//Drawing route when two markers are placed
if(markersArray.size() >= 2){
LatLng origin = markersArray.get(0);
LatLng dest = markersArray.get(1);
String url = getDirectionsUrl(origin, dest);
DownloadTask downloadTask = new DownloadTask();
downloadTask.execute(url);
}
}
/*
* This method places markers on map
*/
private void addMarkerOnMap(LatLng point){
//Marking points on map
options=new MarkerOptions();
options.position(point);
//Setting marker icons
if (markersArray.size()==1) {
//Source marker point
options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
}else if(markersArray.size()==2){
//Destination marker point
options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
}
//adding marker point to map
try{
Marker mMarker=gMap.addMarker(options);
markers.add(mMarker);
}catch(Exception e){
e.printStackTrace();
}
}
/*
* Getting direction url between two points
*
*/
private String getDirectionsUrl(LatLng origin,LatLng dest){
// Origin of route
String str_origin = "origin="+origin.latitude+","+origin.longitude;
// Destination of route
String str_dest = "destination="+dest.latitude+","+dest.longitude;
// Sensor enabled
String sensor = "sensor=false";
// Building the parameters to the web service
String parameters = str_origin+"&"+str_dest+"&"+sensor;
// Output format
String output = "json";
String url = "https://maps.googleapis.com/maps/api/directions/"+output+"?"+parameters;
return url;
}
/*
* passing the direction url
*
*/
private class DownloadTask extends AsyncTask<String, Void, String>{
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog.show();
pDialog.setMessage("Loading route...");
pDialog.setCancelable(false);
}
// Downloading data in non-ui thread
#Override
protected String doInBackground(String... url) {
// For storing data from web service
String data = "";
try{
// Fetching the data from web service
data = downloadUrl(url[0]);
}catch(Exception e){
Log.d("Background Task",e.toString());
}
return data;
}
// Executes in UI thread, after the execution of
// doInBackground()
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
ParserTask parserTask = new ParserTask();
// Invokes the thread for parsing the JSON data
parserTask.execute(result);
}
}
/*
* downloading from url
*
*/
private String downloadUrl(String strUrl) throws IOException{
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try{
URL url = new URL(strUrl);
urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while( ( line = br.readLine()) != null){
sb.append(line);
}
data = sb.toString();
br.close();
}catch(Exception e){
Log.d("Exception while downloading url", e.toString());
}finally{
iStream.close();
urlConnection.disconnect();
}
return data;
}
private class ParserTask extends AsyncTask<String, Integer, List<List<HashMap<String,String>>>>{
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected List<List<HashMap<String, String>>> doInBackground(String... jsonData) {
JSONObject jObject;
List<List<HashMap<String, String>>> routes = null;
try{
jObject = new JSONObject(jsonData[0]);
DirectionsJsonParser parser = new DirectionsJsonParser();
// Starts parsing data
routes = parser.parse(jObject);
}catch(Exception e){
e.printStackTrace();
}
return routes;
}
#Override
protected void onPostExecute(List<List<HashMap<String, String>>> result) {
ArrayList<LatLng> points = null;
PolylineOptions lineOptions = null;
// MarkerOptions markerOptions = new MarkerOptions();
// Traversing through all the routes
for(int i=0;i<result.size();i++){
points = new ArrayList<LatLng>();
lineOptions = new PolylineOptions();
// Fetching i-th route
List<HashMap<String, String>> path = result.get(i);
// Fetching all the points in i-th route
for(int j=0;j<path.size();j++){
HashMap<String,String> point = path.get(j);
if(j==0){ // Get distance from the list
distance = (String)point.get("distance");
continue;
}else if(j==1){ // Get duration from the list
duration = (String)point.get("duration");
continue;
}
double lat = Double.parseDouble(point.get("lat"));
double lng = Double.parseDouble(point.get("lng"));
LatLng position = new LatLng(lat, lng);
points.add(position);
}
// Adding all the points in the route to LineOptions
lineOptions.addAll(points);
lineOptions.width(5);
lineOptions.color(Color.BLUE);
}
// Drawing polyline in the Google Map for the i-th route
try{
gMap.addPolyline(lineOptions);
travelDetails.setText("Distance:"+distance+"Duration:"+duration);
pDialog.dismiss();
}catch (Exception e) {
if (pDialog.isShowing()) {
pDialog.dismiss();
}
Toast.makeText(getApplicationContext(), "No Road route found.", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
}
#Override
protected void onResume() {
super.onResume();
loadMapView();
}
#Override
protected void onPause() {
super.onPause();
mLocationManager.removeUpdates(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.map, menu);
return true;
}
/*
* (non-Javadoc)
* #see com.google.android.gms.maps.LocationSource.OnLocationChangedListener#onLocationChanged(android.location.Location)
*/
#Override
public void onLocationChanged(Location location) {
Log.e("loca", ""+location.getLatitude());
try {
if(markersArray.size()>0){
lattitude=location.getLatitude();
longitude=location.getLongitude();
LatLng mLatLng=new LatLng(lattitude, longitude);
Marker newMarker=markers.get(0);
newMarker.setPosition(mLatLng);
gMap.animateCamera(CameraUpdateFactory.newLatLng(mLatLng));
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
DirectionsJsonParser.java
public class DirectionsJsonParser {
public List<List<HashMap<String,String>>> parse(JSONObject jObject){
List<List<HashMap<String, String>>> routes = new ArrayList<List<HashMap<String,String>>>() ;
JSONArray jRoutes = null;
JSONArray jLegs = null;
JSONArray jSteps = null;
JSONObject jDistance = null;
JSONObject jDuration = null;
try {
jRoutes = jObject.getJSONArray("routes");
for(int i=0;i<jRoutes.length();i++){
jLegs = ( (JSONObject)jRoutes.get(i)).getJSONArray("legs");
List path = new ArrayList<HashMap<String, String>>();
for(int j=0;j<jLegs.length();j++){
jSteps = ( (JSONObject)jLegs.get(j)).getJSONArray("steps");
/** Getting distance from the json data */
jDistance = ((JSONObject) jLegs.get(j)).getJSONObject("distance");
HashMap<String, String> hmDistance = new HashMap<String, String>();
hmDistance.put("distance", jDistance.getString("text"));
/** Getting duration from the json data */
jDuration = ((JSONObject) jLegs.get(j)).getJSONObject("duration");
HashMap<String, String> hmDuration = new HashMap<String, String>();
hmDuration.put("duration", jDuration.getString("text"));
/** Adding distance object to the path */
path.add(hmDistance);
/** Adding duration object to the path */
path.add(hmDuration);
/** Getting poly points */
for(int k=0;k<jSteps.length();k++){
String polyline = "";
polyline = (String)((JSONObject)((JSONObject)jSteps.get(k)).get("polyline")).get("points");
List<LatLng> list = decodePoly(polyline);
for(int l=0;l<list.size();l++){
HashMap<String, String> hm = new HashMap<String, String>();
hm.put("lat", Double.toString(((LatLng)list.get(l)).latitude) );
hm.put("lng", Double.toString(((LatLng)list.get(l)).longitude) );
path.add(hm);
}
}
/** Adding poly points */
routes.add(path);
}
}
} catch (JSONException e) {
e.printStackTrace();
}catch (Exception e){
}
return routes;
}
private List<LatLng> decodePoly(String encoded) {
List<LatLng> poly = new ArrayList<LatLng>();
int index = 0, len = encoded.length();
int lat = 0, lng = 0;
while (index < len) {
int b, shift = 0, result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lat += dlat;
shift = 0;
result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lng += dlng;
LatLng p = new LatLng((((double) lat / 1E5)),
(((double) lng / 1E5)));
poly.add(p);
}
return poly;
}
}
I think you have not used location provider , use googleapiclient
and read about this topic , it allows you to show your current position on map when location changed, that provides you your current locations.
Hint
Implements GoogleApiClient.ConnectionCallbacks , GoogleApiClient.OnConnectionFailedListener
in your activity then you can easily do that.
I am new in developing with android google play sdk.
I want my map have a search function but it only specify on my country.
Let just say i live in Singapore, when i search a location, i want my engine only search on my country. How to set it ??
This is my Java Code
public class NearbyActivity extends FragmentActivity {
Button mBtnFind;
GoogleMap mMap;
EditText etPlace;
LatLng myPosition;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.nearby);
// Getting reference to the find button
mBtnFind = (Button) findViewById(R.id.btn_show);
// Getting reference to the SupportMapFragment
SupportMapFragment mapFragment = (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map);
// Getting reference to the Google Map
mMap = mapFragment.getMap();
// Getting reference to EditText
etPlace = (EditText) findViewById(R.id.et_place);
// Setting click event listener for the find button
mBtnFind.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Getting the place entered
String location = etPlace.getText().toString();
if(location==null || location.equals("")){
Toast.makeText(getBaseContext(), "No Place is entered", Toast.LENGTH_SHORT).show();
return;
}
String url = "https://maps.googleapis.com/maps/api/geocode/json?";
try {
// encoding special characters like space in the user input place
location = URLEncoder.encode(location, "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
String address = "address=" + location;
String sensor = "sensor=false";
// url , from where the geocoding data is fetched
url = url + address + "&" + sensor;
// Instantiating DownloadTask to get places from Google Geocoding service
// in a non-ui thread
DownloadTask downloadTask = new DownloadTask();
// Start downloading the geocoding places
downloadTask.execute(url);
}
});
mMap.setMyLocationEnabled(true);
mMap.getUiSettings().setCompassEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(true);
mMap.getUiSettings().setRotateGesturesEnabled(true);
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// Creating a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Getting the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
// Getting Current Location
Location location = locationManager.getLastKnownLocation(provider);
if(location!=null){
double latitude = location.getLatitude();
double longitude = location.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
myPosition = new LatLng(latitude, longitude);
CameraUpdate center=CameraUpdateFactory.newLatLng(myPosition);
CameraUpdate zoom=CameraUpdateFactory.zoomTo(15);
mMap.moveCamera(center);
mMap.animateCamera(zoom);
mMap.addCircle(new CircleOptions()
.center(myPosition)
.radius(450)
.strokeColor(Color.LTGRAY)
.fillColor(0x2000FFFF));
}
}
private String downloadUrl(String strUrl) throws IOException{
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try{
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while( ( line = br.readLine()) != null){
sb.append(line);
}
data = sb.toString();
br.close();
}catch(Exception e){
Log.d("Exception while downloading url", e.toString());
}finally{
iStream.close();
urlConnection.disconnect();
}
return data;
}
/** A class, to download Places from Geocoding webservice */
private class DownloadTask extends AsyncTask<String, Integer, String>{
String data = null;
// Invoked by execute() method of this object
#Override
protected String doInBackground(String... url) {
try{
data = downloadUrl(url[0]);
}catch(Exception e){
Log.d("Background Task",e.toString());
}
return data;
}
// Executed after the complete execution of doInBackground() method
#Override
protected void onPostExecute(String result){
// Instantiating ParserTask which parses the json data from Geocoding webservice
// in a non-ui thread
ParserTask parserTask = new ParserTask();
// Start parsing the places in JSON format
// Invokes the "doInBackground()" method of the class ParseTask
parserTask.execute(result);
}
}
/** A class to parse the Geocoding Places in non-ui thread */
class ParserTask extends AsyncTask<String, Integer, List<HashMap<String,String>>>{
JSONObject jObject;
// Invoked by execute() method of this object
#Override
protected List<HashMap<String,String>> doInBackground(String... jsonData) {
List<HashMap<String, String>> places = null;
GeocodeJSONParser parser = new GeocodeJSONParser();
try{
jObject = new JSONObject(jsonData[0]);
/** Getting the parsed data as a an ArrayList */
places = parser.parse(jObject);
}catch(Exception e){
Log.d("Exception",e.toString());
}
return places;
}
// Executed after the complete execution of doInBackground() method
#Override
protected void onPostExecute(List<HashMap<String,String>> list){
// Clears all the existing markers
mMap.clear();
for(int i=0;i<list.size();i++){
// Creating a marker
MarkerOptions markerOptions = new MarkerOptions();
// Getting a place from the places list
HashMap<String, String> hmPlace = list.get(i);
// Getting latitude of the place
double lat = Double.parseDouble(hmPlace.get("lat"));
// Getting longitude of the place
double lng = Double.parseDouble(hmPlace.get("lng"));
// Getting name
String name = hmPlace.get("formatted_address");
LatLng latLng = new LatLng(lat, lng);
// Setting the position for the marker
markerOptions.position(latLng);
// Setting the title for the marker
markerOptions.title(name);
// Placing a marker on the touched position
mMap.addMarker(markerOptions);
// Locate the first location
if(i==0)
mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
}
}
}
#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;
}
}
And this is my GEOcodeJSON :
public class GeocodeJSONParser {
/** Receives a JSONObject and returns a list */
public List<HashMap<String,String>> parse(JSONObject jObject){
JSONArray jPlaces = null;
try {
/** Retrieves all the elements in the 'places' array */
jPlaces = jObject.getJSONArray("results");
} catch (JSONException e) {
e.printStackTrace();
}
/** Invoking getPlaces with the array of json object
* where each json object represent a place
*/
return getPlaces(jPlaces);
}
private List<HashMap<String, String>> getPlaces(JSONArray jPlaces){
int placesCount = jPlaces.length();
List<HashMap<String, String>> placesList = new ArrayList<HashMap<String,String>>();
HashMap<String, String> place = null;
/** Taking each place, parses and adds to list object */
for(int i=0; i<placesCount; i++){
try {
/** Call getPlace with place JSON object to parse the place */
place = getPlace((JSONObject)jPlaces.get(i));
placesList.add(place);
} catch (JSONException e) {
e.printStackTrace();
}
}
return placesList;
}
/** Parsing the Place JSON object */
private HashMap<String, String> getPlace(JSONObject jPlace){
HashMap<String, String> place = new HashMap<String, String>();
String formatted_address = "-NA-";
String lat="";
String lng="";
try {
// Extracting formatted address, if available
if(!jPlace.isNull("formatted_address")){
formatted_address = jPlace.getString("formatted_address");
}
lat = jPlace.getJSONObject("geometry").getJSONObject("location").getString("lat");
lng = jPlace.getJSONObject("geometry").getJSONObject("location").getString("lng");
place.put("formatted_address", formatted_address);
place.put("lat", lat);
place.put("lng", lng);
} catch (JSONException e) {
e.printStackTrace();
}
return place;
}
}
You can set a bias for your query to prefer one region. Note that this will only prefer the specific region without excluding all other ones.
Based on your query you will have something like this:
https://maps.googleapis.com/maps/api/geocode/json?address=THEADDRESS®ion=XX&sensor=true
XX is the ccTLD code of the region, e.g. sg for Singapore.