Java tutorial
/* * Copyright (C) 2012 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package pt.bappy.domsebastiao.activities; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import pt.bappy.domsebastiao.R; import pt.bappy.domsebastiao.util.JSONParser; import android.app.ProgressDialog; import android.content.Context; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.os.SystemClock; import android.support.v4.app.FragmentActivity; import android.support.v4.widget.DrawerLayout; import android.view.View; import android.view.View.OnClickListener; import android.view.animation.BounceInterpolator; import android.view.animation.Interpolator; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.GoogleMap.OnInfoWindowClickListener; import com.google.android.gms.maps.GoogleMap.OnMarkerClickListener; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.MarkerOptions; /** * This shows how to place markers on a map. */ public class MapSearchActivity extends FragmentActivity implements OnMarkerClickListener, OnInfoWindowClickListener { private static final String TAG_RESULTS = "results"; private static final String TAG_GEOMETRY = "geometry"; private static final String TAG_VIEWPORT = "viewport"; private static final String TAG_NORTHEAST = "northeast"; private static final String TAG_LAT = "lat"; private static final String TAG_LNG = "lng"; private static final LatLng oFadoRest = new LatLng(51.497587, -0.165078); private static final LatLng oPortalRest = new LatLng(51.522035, -0.101789); private static final LatLng SYDNEY = new LatLng(-33.87365, 151.20689); private static final LatLng ADELAIDE = new LatLng(-34.92873, 138.59995); private static final LatLng PERTH = new LatLng(-31.952854, 115.857342); private EditText et_map_search; private Button bt_map_search; private GoogleMap mMap; private Bundle extras; private Context context; private Marker mPerth; private Marker mSydney; private Marker mBrisbane; private Marker mAdelaide; private Marker mMelbourne; private DrawerLayout drawer_layout; private String[] drawer_items; private ListView lv_drawer; private String lat, lng, address; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_map_results); context = this; extras = getIntent().getExtras(); address = extras.getString("query"); drawer_layout = (DrawerLayout) findViewById(R.id.drawer_layout); drawer_items = getResources().getStringArray(R.array.items); lv_drawer = (ListView) findViewById(R.id.left_drawer); lv_drawer.setAdapter(new ArrayAdapter<String>(this, R.layout.drawer_item, drawer_items)); et_map_search = (EditText) findViewById(R.id.et_map_search); et_map_search.setText(extras.getString("query")); bt_map_search = (Button) findViewById(R.id.bt_map_search); bt_map_search.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { address = et_map_search.getText().toString(); AsyncTask<Object, Void, String> task = new SearchOperation().execute(""); } }); setUpMapIfNeeded(); } @Override protected void onResume() { super.onResume(); setUpMapIfNeeded(); } 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(); mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL); AsyncTask<Object, Void, String> task = new SearchOperation().execute(""); // Check if we were successful in obtaining the map. if (mMap != null) { setUpMap(); } } } private void setUpMap() { // Hide the zoom controls as the button panel will cover it. mMap.getUiSettings().setZoomControlsEnabled(false); // Add lots of markers to the map. addMarkersToMap(); // Set listeners for marker events. See the bottom of this class for // their behavior. mMap.setOnMarkerClickListener(this); mMap.setOnInfoWindowClickListener(this); } private void addMarkersToMap() { // Uses a colored icon. mBrisbane = mMap.addMarker( new MarkerOptions().position(oFadoRest).title("Restaurante").snippet("Restaurante \"O Portal\"") .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE))); // Uses a custom icon with the info window popping out of the center of // the icon. mSydney = mMap .addMarker(new MarkerOptions().position(SYDNEY).title("Sydney").snippet("Population: 4,627,300") .icon(BitmapDescriptorFactory.fromResource(R.drawable.arrow)).infoWindowAnchor(0.5f, 0.5f)); // Creates a draggable marker. Long press to drag. mMelbourne = mMap.addMarker(new MarkerOptions().position(oPortalRest).title("Restaurante") .snippet("Restaurante \"O Portal\"").draggable(true)); // A few more markers for good measure. mPerth = mMap .addMarker(new MarkerOptions().position(PERTH).title("Perth").snippet("Population: 1,738,800")); mAdelaide = mMap.addMarker( new MarkerOptions().position(ADELAIDE).title("Adelaide").snippet("Population: 1,213,000")); } @Override public boolean onMarkerClick(final Marker marker) { final Handler handler = new Handler(); final long start = SystemClock.uptimeMillis(); final long duration = 1500; final Interpolator interpolator = new BounceInterpolator(); handler.post(new Runnable() { @Override public void run() { long elapsed = SystemClock.uptimeMillis() - start; float t = Math.max(1 - interpolator.getInterpolation((float) elapsed / duration), 0); marker.setAnchor(0.5f, 1.0f + 2 * t); if (t > 0.0) { // Post again 16ms later. handler.postDelayed(this, 16); } } }); return false; } private class SearchOperation extends AsyncTask<Object, Void, String> { private ProgressDialog pd; @Override protected String doInBackground(Object... params) { JSONArray results = null; // Creating JSON Parser instance JSONParser jParser = new JSONParser(); address = address.replaceAll(" ", "%20"); String url = "http://maps.googleapis.com/maps/api/geocode/json?address=" + address + "&sensor=true"; // getting JSON string from URL JSONObject json = jParser.getJSONFromUrl(url); try { // Getting Array of results results = json.getJSONArray(TAG_RESULTS); // Toast.makeText(getApplication(), // "Number of results : " + results.length(), // Toast.LENGTH_LONG).show(); for (int i = 0; i < results.length(); i++) { JSONObject r = results.getJSONObject(i); // geometry and location is again JSON Object JSONObject geometry = r.getJSONObject(TAG_GEOMETRY); JSONObject viewport = geometry.getJSONObject(TAG_VIEWPORT); JSONObject northest = viewport.getJSONObject(TAG_NORTHEAST); lat = northest.getString(TAG_LAT); lng = northest.getString(TAG_LNG); } } catch (JSONException e) { e.printStackTrace(); } try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } return "Executed"; } @Override protected void onPostExecute(String result) { pd.dismiss(); mMap.moveCamera( CameraUpdateFactory.newLatLng(new LatLng(Float.parseFloat(lat), Float.parseFloat(lng)))); mMap.animateCamera(CameraUpdateFactory.zoomTo(12), 4000, null); } @Override protected void onPreExecute() { pd = new ProgressDialog(context); pd.setTitle(getResources().getString(R.string.pd_location_title)); pd.setMessage(getResources().getString(R.string.pd_location_message)); pd.setCancelable(false); pd.setIndeterminate(true); pd.show(); } @Override protected void onProgressUpdate(Void... values) { } } @Override public void onInfoWindowClick(Marker marker) { } }