收集几段android代码,关于google map 中overlay部分(转载)


转载自:http://mzba520.iteye.com/blog/96465


AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.example"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:label="@string/app_name" android:icon="@drawable/icon">
        <activity android:name="MyMapActivity"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <uses-library android:name="com.google.android.maps"/>

    </application>
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

</manifest> 


main.xml布局文件:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
        >
    <com.google.android.maps.MapView
            xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@+id/myMapView"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:enabled="true"
            android:clickable="true"
            android:apiKey="0U5iJelzOmytOnZidEAd3J4BLdh46ACaKczkgiQ"
            />

    <LinearLayout android:id="@+id/lay_button"
                  android:layout_width="wrap_content"
                  android:layout_height="wrap_content"
                  android:layout_alignParentBottom="true"
                  android:layout_alignParentLeft="true">
        <ImageButton android:id="@+id/MyImageButton"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                />

    </LinearLayout>

</RelativeLayout>

第一段代码:

package com.example;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.Toast;
import com.google.android.maps.*;

import java.util.List;

public class MyMapActivity extends MapActivity implements View.OnClickListener {
	private MapController myMapController = null;
	private MapView mapView = null;
	private double c_lon = 0;
	private double c_lat = 0;
	private ImageButton myImageButton = null;
	private LocationManager lm = null;

	@Override
	protected boolean isRouteDisplayed() {
		return false;
	}

	@Override
	protected void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		requestWindowFeature(Window.FEATURE_NO_TITLE); //全屏
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
		              WindowManager.LayoutParams.FLAG_FULLSCREEN);
		this.setContentView(R.layout.main);

		mapView = (MapView) this.findViewById(R.id.myMapView);//得到myMapView的引用
		myMapController = mapView.getController();
		myMapController.setZoom(15);                          //设置放大缩小的比例
		mapView.setBuiltInZoomControls(true);                 //设置是否在地图上显示放大缩小按钮

		lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
		String bestProvider = lm.getBestProvider(getCriteria(), true);   //设置查询条件
		Location l = lm.getLastKnownLocation(bestProvider);      //获取用户位置信息
		updateView(l);
		lm.requestLocationUpdates(bestProvider, 1000, 8, ll);    //绑定事件监听

		myImageButton = (ImageButton)findViewById(R.id.MyImageButton);
		myImageButton.setOnClickListener(this);

		MyMapOverlay myOverlay = new MyMapOverlay();
		List<Overlay> overlays = mapView.getOverlays();
		overlays.clear();
		overlays.add(myOverlay);
	}

	public void updateView(Location location){
		if(location != null){
			c_lat = location.getLatitude();
			c_lon = location.getLongitude();
			System.out.println("纬度:"+c_lat+",经度:"+c_lon);
			GeoPoint gp = new GeoPoint((int)(c_lat * 1E6), (int)(c_lon * 1E6));
			myMapController.animateTo(gp);
		}
	}

	public void onClick(View v) {
		if(v == myImageButton){
			boolean flag = true;
			List<Overlay> overlays = mapView.getOverlays();
			for(Overlay overlay:overlays){
				if(overlay instanceof MyBallonOverlay){
					flag = false;
        			GeoPoint gp = ((MyBallonOverlay) overlay).getGeoPoint();
        			Intent intent = new Intent();
        			Bundle bundle = new Bundle();
        			bundle.putDouble("lat", gp.getLatitudeE6()/1E6);
        			bundle.putDouble("lon", gp.getLongitudeE6()/1E6);
        			intent.putExtras(bundle);
        			MyMapActivity.this.setResult(RESULT_OK, intent);
        			MyMapActivity.this.finish();
				}
			}
			if(flag){
        		Toast.makeText(this, "请点击地图获取店铺位置", Toast.LENGTH_LONG).show();
        	}
		}
	}

	public Criteria getCriteria(){
		Criteria c = new Criteria();
		c.setAccuracy(Criteria.ACCURACY_FINE);          //设置查询精度
		c.setSpeedRequired(false);						//设置是否要求速度
		c.setCostAllowed(false);                        //设置是否允许产生费用
		c.setBearingRequired(false);                    //设置是否需要得到方向
		c.setAltitudeRequired(false);                   //设置是否需要得到海拔高度
		c.setPowerRequirement(Criteria.POWER_LOW);      //设置允许的电池消耗级别
		return c;
	}

	LocationListener ll = new LocationListener() {

		public void onStatusChanged(String provider, int status, Bundle extras) {

		}

		public void onProviderEnabled(String provider) {
			//当设备启用时触发事件
			Location l = lm.getLastKnownLocation(provider);
			updateView(l);
		}

		public void onProviderDisabled(String provider) {
			//当设备被禁用时触发事件
			updateView(null);
		}

		public void onLocationChanged(Location location) {
			//当位置改变时触发事件
			updateView(location);
		}
	};
}

第二段代码:

package com.example;

import android.view.MotionEvent;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;

import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: wulong
 * Date: 11-10-31
 * Time: 上午8:29
 * To change this template use File | Settings | File Templates.
 */
//覆盖整个地图捕捉触控事件的OverLay
public class MyMapOverlay extends Overlay {
	boolean flagMove=false;
    @Override
    public boolean onTouchEvent(MotionEvent event, MapView mv) {
        if(event.getAction() == MotionEvent.ACTION_MOVE){//若移动了触控笔则设置移动标志为true
        	flagMove=true;
        }
        else if(event.getAction() == MotionEvent.ACTION_DOWN){//若抬起了触控笔则设置移动标志为false
        	flagMove=false;
        }
        else if (MyBallonOverlay.currentBallon==null&&
        		 !flagMove&&
        		 event.getAction() == MotionEvent.ACTION_UP ){
        	//若没有当前选中的气球也没有移动触控笔且触控笔抬起则获取此处的经纬度并添加新气球
        	GeoPoint gp = mv.getProjection().fromPixels(
        		 (int) event.getX(),  //触控笔在屏幕上的X坐标
        		 (int) event.getY()   //触控笔在屏幕上的Y坐标
            );
        	//显示点击处的经纬度
            String latStr=Math.round(gp.getLatitudeE6()/1000.00)/1000.0+"";//纬度
        	String longStr=Math.round(gp.getLongitudeE6()/1000.00)/1000.0+"";//经度
        	//清除其他气球的showWindow标记
        	List<Overlay> overlays = mv.getOverlays();
        	for(Overlay ol:overlays){//清除其他气球的showWindow标记
        		if(ol instanceof MyBallonOverlay){
        			overlays.remove(ol);
        		}
        	}
        	//在点击位置添加新气球
        	MyBallonOverlay mbo=new MyBallonOverlay(
        			gp,//气球的坐标
        			"店铺位置为:\n经度:"+longStr+"\n纬度:"+latStr//气球的信息
        	);
            overlays.add(mbo);
            return true;
        }
        return false;
    }
}

第三段代码:

package com.example;

import android.graphics.*;
import android.view.MotionEvent;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.Projection;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: wulong
 * Date: 11-10-31
 * Time: 上午8:30
 * To change this template use File | Settings | File Templates.
 */

public class MyBallonOverlay extends Overlay {
	final static int picWidth=20;  //气球图的宽度
	final static int picHeight=34; //气球图的高度
	final static int arcR=8;//信息窗口的圆角半径

	static MyBallonOverlay currentBallon=null;//表示当前选中的气球
	String msg;

	boolean showWindow=false;

	GeoPoint gp;//此气球对应的经纬度

	public MyBallonOverlay(GeoPoint gp,String msg){
		this.gp=gp;
		this.msg=msg;
	}

	public GeoPoint getGeoPoint(){//获得该气球的经纬度GeoPoint
		return gp;
	}

    @Override
    public boolean onTouchEvent(MotionEvent event, MapView mv) {
        if(currentBallon!=null& currentBallon!=this){
        	//若当前气球不为空且不是自己,什么都不做
        	return false;
        }
    	if(event.getAction() == MotionEvent.ACTION_DOWN){
    		//若在气球上按下则设置当前气球为自己,且当前状态为在气球上
        	int x=(int)event.getX();
            int y=(int)event.getY();
            Point p= getPoint(mv);

            int xb=p.x-picWidth/2;
            int yb=p.y-picHeight;

            if(x>=xb&&x<xb+picWidth&&y>=yb&&y<yb+picHeight){
            	//若在自己这个气球上按下则设置自己为当前气球
            	currentBallon=this;
            	return true;
            }
        }
    	else if (event.getAction() == MotionEvent.ACTION_MOVE) {
    		//移动事件返回当前气球状态 若当前在气球上则返回true 屏蔽其他移动事件
    		return currentBallon!=null;
    	}
        else if (event.getAction() == MotionEvent.ACTION_UP) {
        	//获取触控笔位置
            int x=(int)event.getX();
            int y=(int)event.getY();

            //获取气球在屏幕上的坐标范围
            Point p= getPoint(mv);
            int xb=p.x-picWidth/2;
            int yb=p.y-picHeight;

            if(currentBallon==this&&x>=xb&&x<xb+picWidth&&y>=yb&&y<yb+picHeight){
            	//若当前气球为自己且在当前气球上抬起触控则显示当前气球内容
            	//显示完内容后清空当前气球
            	currentBallon=null;
            	showWindow=!showWindow;

            	List<Overlay> overlays = mv.getOverlays();
            	overlays.remove(this);//删除此气球再添加
            	overlays.add(this);//此气球就位于最上面了
            	for(Overlay ol:overlays){//清除其他气球的showWindow标记
            		if(ol instanceof MyBallonOverlay){
            			if(ol!=this){
            				((MyBallonOverlay)ol).showWindow=false;
            			}
            		}
            	}
            	return true;
            }
            else if(currentBallon==this){
            	//若当前气球为自己但抬起触控不再自己上则清空气球状态并返回true
            	currentBallon=null;
            	return true;
            }
        }
        return false;
    }
    @Override
	public void draw(Canvas canvas, MapView mapView, boolean shadow) {
    	//将经纬度翻译成屏幕上的XY坐标
    	Point p= getPoint(mapView);
    	//在坐标指定位置绘制气球
		//canvas.drawBitmap(MainActivity.bitmap, p.x-picWidth/2, p.y-picHeight, null);
        Paint paint = new Paint();
        paint.setAntiAlias(true);
        paint.setColor(Color.BLUE);
        paint.setAlpha(70);
        // 绘制圆形 这里参数就不说明了 上边已经说了
        canvas.drawCircle(p.x-picWidth/2, p.y-picHeight, 40, paint);

		if(showWindow){//如果showWindow为true则显示信息窗口
			drawWindow(canvas,p,160);
		}
		//调用父类绘制
		super.draw(canvas, mapView, shadow);
	}

    public Point getPoint(MapView mapView){//将经纬度翻译成屏幕上的XY坐标
    	Projection projettion = mapView.getProjection();
		Point p = new Point();
		projettion.toPixels(gp, p);
		return p;
    }

	public void drawWindow(Canvas canvas,Point p,int winWidth){//绘制信息窗口的方法
		int charSize=15;
		int textSize=16;
		int leftRightPadding=2;

		//为信息分行
		int lineWidth=winWidth-leftRightPadding*2;//每行的宽度
		int lineCharCount=lineWidth/(charSize);	//每行字符数
		//扫描整个信息字符串分行
		ArrayList<String> alRows=new ArrayList<String>();
		String currentRow="";
		for(int i=0;i<msg.length();i++){
			char c=msg.charAt(i);
			if(c!='\n'){
				currentRow=currentRow+c;
			}
			else{
				if(currentRow.length()>0){
					alRows.add(currentRow);
				}
				currentRow="";
			}
			if(currentRow.length()==lineCharCount){
				alRows.add(currentRow);
				currentRow="";
			}
		}
		if(currentRow.length()>0){
			alRows.add(currentRow);
		}
		int lineCount=alRows.size();//总行数
		int winHeight=lineCount*(charSize)+2*arcR;//窗体高度
		//创建paint对象
		Paint paint=new Paint();
		paint.setAntiAlias(true);
		paint.setTextSize(textSize);
		//绘制 信息窗体圆角矩形
		paint.setARGB(255, 255,251,239);
		int x1=p.x-winWidth/2;
		int y1=p.y-picHeight-winHeight-1;
		int x2=x1+winWidth;
		int y2=y1+winHeight;
		RectF r=new RectF(x1,y1,x2,y2);
		canvas.drawRoundRect(r, arcR, arcR, paint);
		paint.setARGB(255,198,195,198);
		paint.setStyle(Paint.Style.STROKE);
		paint.setStrokeWidth(2);
		canvas.drawRoundRect(r, arcR, arcR, paint);

		//循环绘制每行文字
		paint.setStrokeWidth(0);
		paint.setARGB(255, 10, 10, 10);
		int lineY=y1+arcR+charSize;
		for(String lineStr:alRows){
			for(int j=0;j<lineStr.length();j++){
				String colChar=lineStr.charAt(j)+"";
				canvas.drawText(colChar, x1+leftRightPadding+j*charSize, lineY, paint);
			}
			lineY=lineY+charSize;
		}
	}
}

效果:



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值