Advertisement
Guest User

Untitled

a guest
Jul 29th, 2015
198
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 17.84 KB | None | 0 0
  1. public class MainActivity extends FragmentActivity implements OnTouchListener {
  2.  
  3. private static final String TAG = "polygon";
  4. private GoogleMap mGoogleMap;
  5. private View mMapShelterView;
  6. private GestureDetector mGestureDetector;
  7. private ArrayList<LatLng> mLatlngs = new ArrayList<LatLng>();
  8. private PolylineOptions mPolylineOptions;
  9. private PolygonOptions mPolygonOptions;
  10. // flag to differentiate whether user is touching to draw or not
  11. private boolean mDrawFinished = false;
  12.  
  13. @Override
  14. protected void onCreate(Bundle savedInstanceState) {
  15. super.onCreate(savedInstanceState);
  16. setContentView(R.layout.activity_main);
  17. mMapShelterView = (View) findViewById(R.id.drawer_view);
  18. mGestureDetector = new GestureDetector(this, new GestureListener());
  19. mMapShelterView.setOnTouchListener(this);
  20. initilizeMap();
  21. //Contains(null);
  22. }
  23.  
  24. private final class GestureListener extends SimpleOnGestureListener {
  25. @Override
  26. public boolean onDown(MotionEvent e) {
  27. return true;
  28. }
  29.  
  30. @Override
  31. public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
  32. float velocityY) {
  33. return false;
  34. }
  35. }
  36.  
  37. /**
  38. * Ontouch event will draw poly line along the touch points
  39. *
  40. */
  41. @Override
  42. public boolean onTouch(View v, MotionEvent event) {
  43. int X1 = (int) event.getX();
  44. int Y1 = (int) event.getY();
  45. Point point = new Point();
  46. point.x = X1;
  47. point.y = Y1;
  48. LatLng firstGeoPoint = mGoogleMap.getProjection().fromScreenLocation(
  49. point);
  50. switch (event.getAction()) {
  51.  
  52. case MotionEvent.ACTION_DOWN:
  53. break;
  54.  
  55. case MotionEvent.ACTION_MOVE:
  56. if (mDrawFinished) {
  57. X1 = (int) event.getX();
  58. Y1 = (int) event.getY();
  59. point = new Point();
  60. point.x = X1;
  61. point.y = Y1;
  62. LatLng geoPoint = mGoogleMap.getProjection()
  63. .fromScreenLocation(point);
  64. mLatlngs.add(geoPoint);
  65. mPolylineOptions = new PolylineOptions();
  66. mPolylineOptions.color(Color.RED);
  67. mPolylineOptions.width(3);
  68. mPolylineOptions.addAll(mLatlngs);
  69. mGoogleMap.addPolyline(mPolylineOptions);
  70. **Log.d(TAG, "Latitude and longitude: " + mLatlngs);**
  71.  
  72. }
  73. break;
  74. case MotionEvent.ACTION_UP:
  75. Log.d(TAG, "Poinnts array size " + mLatlngs.size());
  76. mLatlngs.add(firstGeoPoint);
  77. mGoogleMap.clear();
  78. mPolylineOptions = null;
  79. mMapShelterView.setVisibility(View.GONE);
  80. mGoogleMap.getUiSettings().setZoomGesturesEnabled(true);
  81. mGoogleMap.getUiSettings().setAllGesturesEnabled(true);
  82. mPolygonOptions = new PolygonOptions();
  83. mPolygonOptions.fillColor(0x5500ff00);
  84. // mPolygonOptions.fillColor(Color.LTGRAY);
  85. mPolygonOptions.strokeColor(Color.RED);
  86. mPolygonOptions.strokeWidth(5);
  87. mPolygonOptions.addAll(mLatlngs);
  88. mGoogleMap.addPolygon(mPolygonOptions);
  89. mDrawFinished = false;
  90. break;
  91. }
  92. return mGestureDetector.onTouchEvent(event);
  93. }
  94.  
  95. /**
  96. * Setting up map
  97. *
  98. */
  99.  
  100. private void initilizeMap() {
  101. int status = GooglePlayServicesUtil
  102. .isGooglePlayServicesAvailable(getApplicationContext());
  103. if (status == ConnectionResult.SUCCESS) {
  104. if (mGoogleMap == null) {
  105. mGoogleMap = ((SupportMapFragment) getSupportFragmentManager()
  106. .findFragmentById(R.id.map)).getMap();
  107. mGoogleMap.setMyLocationEnabled(true);
  108.  
  109. }
  110.  
  111. } else if (GooglePlayServicesUtil.isUserRecoverableError(status)) {
  112. // showErrorDialog(status);
  113. } else {
  114. Toast.makeText(this, "No Support for Google Play Service",
  115. Toast.LENGTH_LONG).show();
  116. }
  117. }
  118.  
  119. /**
  120. * Method gets called on tap of draw button, It prepares the screen to draw
  121. * the polygon
  122. *
  123. * @param view
  124. */
  125.  
  126. public void drawZone(View view) {
  127. mGoogleMap.clear();
  128. mLatlngs.clear();
  129. mPolylineOptions = null;
  130. mPolygonOptions = null;
  131. mDrawFinished = true;
  132. mMapShelterView.setVisibility(View.VISIBLE);
  133. mGoogleMap.getUiSettings().setScrollGesturesEnabled(false);
  134. }
  135.  
  136. public synchronized boolean Contains(Location location) {
  137. boolean isInside = false;
  138.  
  139. if (mLatlngs.size() > 0) {
  140. LatLng lastPoint = mLatlngs.get(mLatlngs.size() - 1);
  141.  
  142. double x = location.getLongitude();
  143.  
  144. for (LatLng point : mLatlngs) {
  145. double x1 = lastPoint.longitude;
  146. double x2 = point.longitude;
  147. double dx = x2 - x1;
  148.  
  149. if (Math.abs(dx) > 180.0) {
  150. if (x > 0) {
  151. while (x1 < 0)
  152. x1 += 360;
  153. while (x2 < 0)
  154. x2 += 360;
  155. } else {
  156. while (x1 > 0)
  157. x1 -= 360;
  158. while (x2 > 0)
  159. x2 -= 360;
  160. }
  161. dx = x2 - x1;
  162. }
  163.  
  164. if ((x1 <= x && x2 > x) || (x1 >= x && x2 < x)) {
  165. double grad = (point.latitude - lastPoint.latitude) / dx;
  166. double intersectAtLat = lastPoint.latitude
  167. + ((x - x1) * grad);
  168.  
  169. if (intersectAtLat > location.getLatitude())
  170. isInside = !isInside;
  171. }
  172. lastPoint = point;
  173. }
  174. }
  175.  
  176. return isInside;
  177. }
  178.  
  179. public StringBuilder sbMethod() {
  180.  
  181. //use your current location here
  182. double mLatitude = 37.77657;
  183. double mLongitude = -122.417506;
  184.  
  185. StringBuilder sb = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
  186. sb.append("location=" + mLatitude + "," + mLongitude);
  187. sb.append("&radius=5000");
  188. sb.append("&types=" + "restaurant");
  189. sb.append("&sensor=true");
  190. sb.append("&key=******* YOUR API KEY****************");
  191.  
  192. Log.d("Map", "api: " + sb.toString());
  193.  
  194. return sb;
  195. }
  196.  
  197. private class PlacesTask extends AsyncTask<String, Integer, String> {
  198.  
  199. String data = null;
  200.  
  201. // Invoked by execute() method of this object
  202. @Override
  203. protected String doInBackground(String... url) {
  204. try {
  205. data = downloadUrl(url[0]);
  206. } catch (Exception e) {
  207. Log.d("Background Task", e.toString());
  208. }
  209. return data;
  210. }
  211.  
  212. // Executed after the complete execution of doInBackground() method
  213. @Override
  214. protected void onPostExecute(String result) {
  215. ParserTask parserTask = new ParserTask();
  216.  
  217. // Start parsing the Google places in JSON format
  218. // Invokes the "doInBackground()" method of the class ParserTask
  219. parserTask.execute(result);
  220. }
  221. }
  222.  
  223. private String downloadUrl(String strUrl) throws IOException {
  224. String data = "";
  225. InputStream iStream = null;
  226. HttpURLConnection urlConnection = null;
  227. try {
  228. URL url = new URL(strUrl);
  229.  
  230. // Creating an http connection to communicate with url
  231. urlConnection = (HttpURLConnection) url.openConnection();
  232.  
  233. // Connecting to url
  234. urlConnection.connect();
  235.  
  236. // Reading data from url
  237. iStream = urlConnection.getInputStream();
  238.  
  239. BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
  240.  
  241. StringBuffer sb = new StringBuffer();
  242.  
  243. String line = "";
  244. while ((line = br.readLine()) != null) {
  245. sb.append(line);
  246. }
  247.  
  248. data = sb.toString();
  249.  
  250. br.close();
  251.  
  252. } catch (Exception e) {
  253. Log.d("Exception while downloading url", e.toString());
  254. } finally {
  255. iStream.close();
  256. urlConnection.disconnect();
  257. }
  258. return data;
  259. }
  260.  
  261. private class ParserTask extends AsyncTask<String, Integer, List<HashMap<String, String>>> {
  262.  
  263. JSONObject jObject;
  264.  
  265. // Invoked by execute() method of this object
  266. @Override
  267. protected List<HashMap<String, String>> doInBackground(String... jsonData) {
  268.  
  269. List<HashMap<String, String>> places = null;
  270. Place_JSON placeJson = new Place_JSON();
  271.  
  272. try {
  273. jObject = new JSONObject(jsonData[0]);
  274.  
  275. places = placeJson.parse(jObject);
  276.  
  277. } catch (Exception e) {
  278. Log.d("Exception", e.toString());
  279. }
  280. return places;
  281. }
  282.  
  283. // Executed after the complete execution of doInBackground() method
  284. @Override
  285. protected void onPostExecute(List<HashMap<String, String>> list) {
  286.  
  287. Log.d("Map", "list size: " + list.size());
  288. // Clears all the existing markers;
  289. mGoogleMap.clear();
  290.  
  291. for (int i = 0; i < list.size(); i++) {
  292.  
  293. // Creating a marker
  294. MarkerOptions markerOptions = new MarkerOptions();
  295.  
  296. // Getting a place from the places list
  297. HashMap<String, String> hmPlace = list.get(i);
  298.  
  299.  
  300. // Getting latitude of the place
  301. double lat = Double.parseDouble(hmPlace.get("lat"));
  302.  
  303. // Getting longitude of the place
  304. double lng = Double.parseDouble(hmPlace.get("lng"));
  305.  
  306. // Getting name
  307. String name = hmPlace.get("place_name");
  308.  
  309. Log.d("Map", "place: " + name);
  310.  
  311. // Getting vicinity
  312. String vicinity = hmPlace.get("vicinity");
  313.  
  314. LatLng latLng = new LatLng(lat, lng);
  315.  
  316. // Setting the position for the marker
  317. markerOptions.position(latLng);
  318.  
  319. markerOptions.title(name + " : " + vicinity);
  320.  
  321. markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
  322.  
  323. // Placing a marker on the touched position
  324. Marker m = mGoogleMap.addMarker(markerOptions);
  325.  
  326. }
  327. }
  328. }
  329.  
  330. public class Place_JSON {
  331.  
  332. /**
  333. * Receives a JSONObject and returns a list
  334. */
  335. public List<HashMap<String, String>> parse(JSONObject jObject) {
  336.  
  337. JSONArray jPlaces = null;
  338. try {
  339. /** Retrieves all the elements in the 'places' array */
  340. jPlaces = jObject.getJSONArray("results");
  341. } catch (JSONException e) {
  342. e.printStackTrace();
  343. }
  344. /** Invoking getPlaces with the array of json object
  345. * where each json object represent a place
  346. */
  347. return getPlaces(jPlaces);
  348. }
  349.  
  350. private List<HashMap<String, String>> getPlaces(JSONArray jPlaces) {
  351. int placesCount = jPlaces.length();
  352. List<HashMap<String, String>> placesList = new ArrayList<HashMap<String, String>>();
  353. HashMap<String, String> place = null;
  354.  
  355. /** Taking each place, parses and adds to list object */
  356. for (int i = 0; i < placesCount; i++) {
  357. try {
  358. /** Call getPlace with place JSON object to parse the place */
  359. place = getPlace((JSONObject) jPlaces.get(i));
  360. placesList.add(place);
  361. } catch (JSONException e) {
  362. e.printStackTrace();
  363. }
  364. }
  365. return placesList;
  366. }
  367.  
  368. /**
  369. * Parsing the Place JSON object
  370. */
  371. private HashMap<String, String> getPlace(JSONObject jPlace) {
  372.  
  373. HashMap<String, String> place = new HashMap<String, String>();
  374. String placeName = "-NA-";
  375. String vicinity = "-NA-";
  376. String latitude = "";
  377. String longitude = "";
  378. String reference = "";
  379.  
  380. try {
  381. // Extracting Place name, if available
  382. if (!jPlace.isNull("name")) {
  383. placeName = jPlace.getString("name");
  384. }
  385.  
  386. // Extracting Place Vicinity, if available
  387. if (!jPlace.isNull("vicinity")) {
  388. vicinity = jPlace.getString("vicinity");
  389. }
  390.  
  391. latitude = jPlace.getJSONObject("geometry").getJSONObject("location").getString("lat");
  392. longitude = jPlace.getJSONObject("geometry").getJSONObject("location").getString("lng");
  393. reference = jPlace.getString("reference");
  394.  
  395. place.put("place_name", placeName);
  396. place.put("vicinity", vicinity);
  397. place.put("lat", latitude);
  398. place.put("lng", longitude);
  399. place.put("reference", reference);
  400.  
  401. } catch (JSONException e) {
  402. e.printStackTrace();
  403. }
  404. return place;
  405. }
  406. }
  407.  
  408. StringBuilder sbValue = new StringBuilder(sbMethod());
  409. PlacesTask placesTask = new PlacesTask();
  410. placesTask.execute(sbValue.toString());
  411.  
  412. <uses-permission android:name="in.wptrafficanalyzer.locationgeocodingv2.permission.MAPS_RECEIVE" />
  413. <uses-permission android:name="android.permission.INTERNET" />
  414. <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
  415. <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
  416. <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
  417. <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
  418. <uses-feature
  419. android:glEsVersion="0x00020000"
  420. android:required="true" />
  421. <meta-data
  422. android:name="com.google.android.maps.v2.API_KEY"
  423. android:value="your API Key" />
  424.  
  425. package in.wptrafficanalyzer.locationgeocodingv2;
  426.  
  427. import java.io.IOException;
  428. import java.util.List;
  429.  
  430. import android.location.Address;
  431. import android.location.Geocoder;
  432. import android.os.AsyncTask;
  433. import android.os.Bundle;
  434. import android.support.v4.app.FragmentActivity;
  435. import android.view.Menu;
  436. import android.view.View;
  437. import android.view.View.OnClickListener;
  438. import android.widget.AutoCompleteTextView;
  439. import android.widget.Button;
  440. import android.widget.EditText;
  441. import android.widget.Toast;
  442.  
  443. import com.google.android.gms.maps.CameraUpdateFactory;
  444. import com.google.android.gms.maps.GoogleMap;
  445. import com.google.android.gms.maps.SupportMapFragment;
  446. import com.google.android.gms.maps.model.LatLng;
  447. import com.google.android.gms.maps.model.MarkerOptions;
  448.  
  449. public class MainActivity extends FragmentActivity {
  450.  
  451. GoogleMap googleMap;
  452. MarkerOptions markerOptions;
  453. LatLng latLng;
  454. private AutoCompleteTextView actv_Serch;
  455.  
  456. @Override
  457. protected void onCreate(Bundle savedInstanceState) {
  458. super.onCreate(savedInstanceState);
  459. setContentView(R.layout.activity_main);
  460.  
  461. SupportMapFragment supportMapFragment = (SupportMapFragment) getSupportFragmentManager()
  462. .findFragmentById(R.id.map);
  463.  
  464. // Getting a reference to the map
  465. googleMap = supportMapFragment.getMap();
  466.  
  467. // Getting reference to btn_find of the layout activity_main
  468. Button btn_find = (Button) findViewById(R.id.btn_find);
  469.  
  470. // Defining button click event listener for the find button
  471. OnClickListener findClickListener = new OnClickListener() {
  472. @Override
  473. public void onClick(View v) {
  474. // Getting reference to EditText to get the user input location
  475. // EditText etLocation = (EditText)
  476. // findViewById(R.id.et_location);
  477. actv_Serch = (AutoCompleteTextView) findViewById(R.id.actv_Search);
  478.  
  479. // Getting user input location
  480. String location = actv_Serch.getText().toString();
  481.  
  482. if (location != null && !location.equals("")) {
  483. new GeocoderTask().execute(location);
  484. }
  485. }
  486. };
  487.  
  488. // Setting button click event listener for the find button
  489. btn_find.setOnClickListener(findClickListener);
  490.  
  491. }
  492.  
  493. @Override
  494. public boolean onCreateOptionsMenu(Menu menu) {
  495. // Inflate the menu; this adds items to the action bar if it is present.
  496. getMenuInflater().inflate(R.menu.activity_main, menu);
  497. return true;
  498. }
  499.  
  500. // An AsyncTask class for accessing the GeoCoding Web Service
  501. private class GeocoderTask extends AsyncTask<String, Void, List<Address>> {
  502.  
  503. @Override
  504. protected List<Address> doInBackground(String... locationName) {
  505. // Creating an instance of Geocoder class
  506. Geocoder geocoder = new Geocoder(getBaseContext());
  507. List<Address> addresses = null;
  508.  
  509. try {
  510. // Getting a maximum of 3 Address that matches the input text
  511. addresses = geocoder.getFromLocationName(locationName[0], 3);
  512. } catch (IOException e) {
  513. e.printStackTrace();
  514. }
  515. return addresses;
  516. }
  517.  
  518. @Override
  519. protected void onPostExecute(List<Address> addresses) {
  520.  
  521. if (addresses == null || addresses.size() == 0) {
  522. Toast.makeText(getBaseContext(), "No Location found",
  523. Toast.LENGTH_SHORT).show();
  524. }
  525.  
  526. // Clears all the existing markers on the map
  527. googleMap.clear();
  528.  
  529. // Adding Markers on Google Map for each matching address
  530. for (int i = 0; i < addresses.size(); i++) {
  531.  
  532. Address address = (Address) addresses.get(i);
  533.  
  534. // Creating an instance of GeoPoint, to display in Google Map
  535. latLng = new LatLng(address.getLatitude(),
  536. address.getLongitude());
  537.  
  538. String addressText = String.format(
  539. "%s, %s",
  540. address.getMaxAddressLineIndex() > 0 ? address
  541. .getAddressLine(0) : "", address
  542. .getCountryName());
  543.  
  544. markerOptions = new MarkerOptions();
  545. markerOptions.position(latLng);
  546. markerOptions.title(addressText);
  547.  
  548. googleMap.addMarker(markerOptions);
  549.  
  550. // Locate the first location
  551. if (i == 0)
  552. googleMap.animateCamera(CameraUpdateFactory
  553. .newLatLng(latLng));
  554. }
  555. }
  556. }
  557. }
  558.  
  559. PlacesTask placesTask = new PlacesTask();
  560. placesTask.execute(sbValue.toString());
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement