Map.java :  » Location » unwired-hotspots » org » imaxim » unwired » Android Open Source

Android Open Source » Location » unwired hotspots 
unwired hotspots » org » imaxim » unwired » Map.java
/*
 * This file is part of unwired-hotspots application
 *
 * unwired-hotspots is free software: you can redistribute it
 * and/or modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation, either version 3 of
 * the License, or (at your option) any later version.
 *
 * unwired-hotspots is distributed in the hope that it will be
 * useful, but WITHOUT ANY WARRANTY; without even the implied warranty
 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with unwired-hotspots.  If not, see
 * <http://www.gnu.org/licenses/>.
 */


package org.imaxim.unwired;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

import org.imaxim.unwired.domain.*;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.drawable.Drawable;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ZoomControls;

public class Map extends MapActivity 
{
  LinearLayout linearLayout;
  MapView mapView;
  MapController mapController;
  List<Overlay> mapOverlays;
  Drawable mMyLocationIcon;
  Drawable mHotspotIcon;
  UnwiredItemizedOverlay itemizedOverlay;
  ZoomControls mZoom;
  TextView title;
  MyLocationOverlay myLocationOverlay;
  GeoLocation mMyLocation;
  private ProgressDialog progressDialog;
  HotspotList mHotspotList;
  HotspotDetails mHotspotDetails;
  
  
  final int MENU_MY_LOCATION = 1;
  final int MENU_SET_LOCATION = 2;
  final int MENU_EXIT = 3;
  
  final int MESSAGE_DISPLAY_HOTSPOTS = 1;
  public final int GET_LOCATION_DETAILS = 2;
  public final int DISPLAY_LOCATION_DETAILS = 3;
  
  public final Handler handler = new Handler() 
  {
        @Override
        public void handleMessage(final Message msg)
        {
          switch(msg.arg1)
          {
            case MESSAGE_DISPLAY_HOTSPOTS:
              progressDialog.dismiss();
                displayHotspots();
                break;
                
            case GET_LOCATION_DETAILS:
              getLocationDetails(msg.arg2);
              break;
                
            case DISPLAY_LOCATION_DETAILS:
              progressDialog.dismiss(); 
                  displayDetails();
              break;
          }
          
        }
    };
    
    private void getLocationDetails(final int id)
    {
      this.progressDialog = ProgressDialog.show(this, " Working...", "Getting hotspot details", true, false);
      new Thread() 
        {
            @Override public void run() 
            {
              mHotspotDetails = new DataProvider().getHotspotDetails(id);
          Message newMessage = new Message();
          newMessage.arg1 = DISPLAY_LOCATION_DETAILS;
              handler.sendMessage(newMessage);
            }
          }.start();
    }
    
    private void displayDetails()
  {
      new AlertDialog.Builder(this)
        .setTitle(mHotspotDetails.getTitle())
        .setMessage(mHotspotDetails.getAddress() +
            "\n" + mHotspotDetails.getTown() + " " + mHotspotDetails.getPostcode() + " " + mHotspotDetails.getState() +
            "\n" + mHotspotDetails.getTelephone())
        .setNeutralButton("Ok",  new DialogInterface.OnClickListener()    {
        public void onClick(DialogInterface dialog,  int which) {   }
      }).show();
  }
  
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        mapView = (MapView) findViewById(R.id.mapview);
        mapView.setBuiltInZoomControls(true);
        
        mapOverlays = mapView.getOverlays();
        myLocationOverlay = new MyLocationOverlay(this, mapView);
        
        mapOverlays.add(myLocationOverlay);
        mapController = mapView.getController();

        mMyLocationIcon = this.getResources().getDrawable(R.drawable.mylocation);
        mMyLocationIcon.setBounds(0,0, 64, 64); 
        mHotspotIcon = this.getResources().getDrawable(R.drawable.unwired);
        
        InitLocationUpdates();
    }
    
    @Override
    public void onResume() 
    {
      super.onResume();
      myLocationOverlay.enableMyLocation();
    }
    
    @Override
    public void onPause() 
    {
      super.onPause();
      myLocationOverlay.disableMyLocation();
    }
    
    private void InitLocationUpdates()
    {
      LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
      
      Criteria criteria = new Criteria();
      criteria.setAccuracy(Criteria.ACCURACY_FINE);
      criteria.setAltitudeRequired(false);
      criteria.setBearingRequired(false);
      criteria.setCostAllowed(true);
      criteria.setPowerRequirement(Criteria.POWER_LOW);

      String provider = locationManager.getBestProvider(criteria, true);
      
      locationManager.requestLocationUpdates(provider,
                180000, // 3min
                500,   // 5km
                locationListener);
      
      locationListener.onLocationChanged(locationManager.getLastKnownLocation(provider));

    }
    
    private void updateWithNewLocation(GeoLocation location)
    {
      if(location == null) return;

      GeoPoint geopoint = location.getGeoPoint();
  
        mapController.animateTo(geopoint);
        mapController.zoomToSpan(30000, 30000);
        
        final GeoLocation location2 = location;
        
        this.progressDialog = ProgressDialog.show(this, " Working...", "Getting hotspot data", true, false);
        
        new Thread() 
        {
            @Override public void run() 
            {
              mHotspotList = new DataProvider().getHotspots(location2);
              
              Message message = new Message();
              message.arg1 = MESSAGE_DISPLAY_HOTSPOTS;
              
              handler.sendMessage(message);
            }
          }.start();
    }
    
    private void displayHotspots()
    {
      if(itemizedOverlay != null)
        mapOverlays.remove(itemizedOverlay);
      
      itemizedOverlay = new UnwiredItemizedOverlay(this, mHotspotIcon);
      for(Hotspot hotspot : mHotspotList.values())
      {
        GeoPoint geopoint = hotspot.getLocation().getGeoPoint();
        OverlayItem overlayItem = new OverlayItem(geopoint, "Hotspot", String.format("%d", hotspot.getId()));
        overlayItem.setMarker(mHotspotIcon);
        itemizedOverlay.add(overlayItem);
      }
      itemizedOverlay.populateItems();
      mapOverlays.add(itemizedOverlay);
    }
    
    private final LocationListener locationListener = new LocationListener() 
    {
        public void onLocationChanged(Location location) 
        {
          if(location == null)
            return;
          
          mMyLocation = new GeoLocation(location.getLatitude(), location.getLongitude());
          updateWithNewLocation(mMyLocation);
        }

        public void onProviderDisabled(String provider){}
        public void onProviderEnabled(String provider) {}
        public void onStatusChanged(String provider, int status, Bundle extras) {}
    };
    
    private void displayToastMessage(String message)
    {
      Toast.makeText(this, message, Toast.LENGTH_LONG).show();
    }
    
    private void setLocation()
    {
      AlertDialog.Builder alert = new AlertDialog.Builder(this);

      alert.setTitle("Set location");
      alert.setMessage("Please enter location name");

      // Set an EditText view to get user input 
      final EditText input = new EditText(this);
      alert.setView(input);

      alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() 
      {
        public void onClick(DialogInterface dialog, int whichButton) 
        {
          String value = input.getText().toString();
          GeoLocation location = geocodeLocation(value);
          if(location == null)
            displayToastMessage("Not found");
          else
            updateWithNewLocation(location);
        }
      });

      alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() 
      {
        public void onClick(DialogInterface dialog, int whichButton) { }
      });

      alert.show();
    }
    
    private GeoLocation geocodeLocation(String location)
    {
      Geocoder geoCoder = new Geocoder(this, Locale.getDefault());    
        try 
        {
            List<Address> addresses = geoCoder.getFromLocationName(location, 5);
            return (addresses.size() > 0)
              ? new GeoLocation(addresses.get(0).getLatitude(), addresses.get(0).getLongitude())
              : null; 
        } 
        catch (IOException e) 
        {
            return null;
        }
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) 
    {
      if(mMyLocation != null)
      {
        MenuItem myLocationMenuItem = menu.add(0, MENU_MY_LOCATION, 0, "My location");
        myLocationMenuItem.setIcon(android.R.drawable.ic_menu_mylocation);
      }
      MenuItem setLocationMenuItem = menu.add(0, MENU_SET_LOCATION, 0, "Set location");
      setLocationMenuItem.setIcon(android.R.drawable.ic_menu_compass);
      MenuItem exitMenuItem = menu.add(0, MENU_EXIT, 0, "Exit");
      exitMenuItem.setIcon(android.R.drawable.ic_menu_close_clear_cancel);
      return true;
    }

    public boolean onOptionsItemSelected(MenuItem item) 
    {
        switch (item.getItemId()) 
        {
          case MENU_MY_LOCATION:
            updateWithNewLocation(mMyLocation);
              return true;
              
          case MENU_SET_LOCATION:
            setLocation();
              return true;
              
          case MENU_EXIT:
            finish();
              return true;
        }
        return false;
    }
    
  @Override
  protected boolean isRouteDisplayed() 
  {
    return false;
  }
}
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.