我想在Google地图上实现自定义模块免费绘图.当涉及到实现时,我发现Google Map onDrag()回调并且总是覆盖我的自定义onDrag()函数.我不太清楚如何使用我的FrameLayout onDrag()覆盖地图点击并拖动动作.

这是我的工作:

XML:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/Locinfo"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />


    <fragment
        android:id="@+id/map"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        class="com.example.androidmapsv2.CustomMapFragment" >
    </fragment>

    <FrameLayout
        android:id="@+id/fram_map"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
    </FrameLayout>

</LinearLayout>

CustomMapFragment.java

package com.example.androidmapsv2;

import com.google.android.gms.maps.MapFragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class CustomMapFragment extends MapFragment {
     public View mOriginalContentView;
        public MapWrapperLayout mMapWrapperLayout;

        @Override
        public View onCreateView(LayoutInflater inflater,ViewGroup parent,Bundle savedInstanceState) {

            mOriginalContentView = super.onCreateView(inflater,parent,savedInstanceState);
            mMapWrapperLayout = new MapWrapperLayout(getActivity());
            mMapWrapperLayout.addView(mOriginalContentView);
            return mMapWrapperLayout;
        }

        @Override
        public View getView() {
            return mOriginalContentView;
        }

        public void setonDragListener(MapWrapperLayout.OnDragListener onDragListener) {
            mMapWrapperLayout.setonDragListener(onDragListener);
        }
}

MapWrapperLayout.java

public class MapWrapperLayout extends FrameLayout {
    private OnDragListener mOnDragListener;

    public MapWrapperLayout(Context context) {
        super(context);
    }

    public interface OnDragListener {
        public void onDrag(MotionEvent motionEvent);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (mOnDragListener != null) {
            mOnDragListener.onDrag(ev);
        }
        return super.dispatchTouchEvent(ev);
    }

    public void setonDragListener(OnDragListener mOnDragListener) {
        this.mOnDragListener = mOnDragListener;
    }

}

MainActivity.java

package com.example.androidmapsv2;

import java.util.ArrayList;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
import com.google.android.gms.maps.GoogleMap.OnMapLongClickListener;
import com.google.android.gms.maps.GoogleMap.OnMarkerClickListener;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.Projection;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.polygon;
import com.google.android.gms.maps.model.polygonoptions;
import com.google.android.gms.maps.model.polylineoptions;

import android.app.Activity;
import android.app.FragmentManager;
import android.graphics.Color;
import android.graphics.Point;
import android.location.Location;
import android.os.Bundle;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity 
    implements OnMapClickListener {

    final int RQS_GooglePlayServices = 1;
    private GoogleMap myMap;

    Location myLocation;
    TextView tvLocinfo;
    ArrayList<LatLng> val = new ArrayList<LatLng>();  
    boolean markerClicked;
    polygonoptions polygonoptions;
    polygon polygon;
    FrameLayout fram_map;
    CustomMapFragment myMapFragment ;
    boolean Is_MAP_Moveable;  
    Projection projection;
    public double latitude;
    public double longitude;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tvLocinfo = (TextView)findViewById(R.id.Locinfo);

        FragmentManager myFragmentManager = getFragmentManager();
         myMapFragment 
            = (CustomMapFragment)myFragmentManager.findFragmentById(R.id.map);

        if (myMapFragment != null) {

            myMapFragment.getMapAsync(new OnMapReadyCallback() {
                @Override
                public void onMapReady(GoogleMap map) {
                    loadMap(map);
                }
            });


            fram_map = (FrameLayout) findViewById(R.id.fram_map);
            Is_MAP_Moveable = false; // to detect map is movable 



        } else {
            Toast.makeText(this,"Error - Map Fragment was null!!",Toast.LENGTH_SHORT).show();

        }


    }

    public void Draw_Map() {


        myMap.addpolyline(new polylineoptions()
                .addAll(val)
                .color(Color.parseColor( "#0971b2")).width(10f));

    }


    protected void loadMap(GoogleMap map) {
        // Todo Auto-generated method stub
        myMap = map;
        myMap.setMyLocationEnabled(true);

        myMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);

        myMap.setonMapClickListener(this);
        //myMap.setonMapLongClickListener(this);
        //myMap.setonMarkerClickListener(this);

        markerClicked = false;
        fram_map.setonTouchListener(new View.OnTouchListener() {   
            @Override
            public boolean onTouch(View v,MotionEvent event) {
                float x = event.getX();
                float y = event.getY();

                int x_co = Math.round(x);
                int y_co = Math.round(y);

                projection = myMap.getProjection();
                Point x_y_points = new Point(x_co,y_co);

                LatLng latLng = myMap.getProjection().fromScreenLocation(x_y_points);
                latitude = latLng.latitude;

                longitude = latLng.longitude;

                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        // finger touches the screen
                        val.add(new LatLng(latitude,longitude));

                    case MotionEvent.ACTION_MOVE:
                        // finger moves on the screen
                        val.add(new LatLng(latitude,longitude));

                    case MotionEvent.ACTION_UP:
                       v.performClick();

                        // finger leaves the screen
                         Draw_Map();
                        break;
                }

                if (Is_MAP_Moveable == true) {
                    return true;

                } else {
                    return false;
                }
            }
        });

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main,menu);
        return true;
    }


    @Override
    protected void onResume() {

        super.onResume();

        int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext());

        if (resultCode == ConnectionResult.SUCCESS){
            Toast.makeText(getApplicationContext(),"isGooglePlayServicesAvailable SUCCESS",Toast.LENGTH_LONG).show();
        }else{
            GooglePlayServicesUtil.getErrorDialog(resultCode,this,RQS_GooglePlayServices);
        }

    }

    @Override
    public void onMapClick(LatLng point) {

        Is_MAP_Moveable = !Is_MAP_Moveable;
        Toast.makeText(getApplicationContext(),Is_MAP_Moveable ? "drawing activated" : "drawing disabled",Toast.LENGTH_SHORT).show();
//      tvLocinfo.setText(point.toString());
//      myMap.animateCamera(CameraUpdateFactory.newLatLng(point));
//      
//      markerClicked = false;
    }

//  @Override
//  public void onMapLongClick(LatLng point) {
//      tvLocinfo.setText("New marker added@" + point.toString());
//      myMap.addMarker(new MarkerOptions().position(point).title(point.toString()));
//      
//      markerClicked = false;
//  }
//
//  @Override
//  public boolean onMarkerClick(Marker marker) {
//      
//      if(markerClicked){
//          
//          if(polygon != null){
//              polygon.remove();
//              polygon = null;
//          }
//          
//          polygonoptions.add(marker.getPosition());
//          polygonoptions.strokeColor(Color.RED);
//          polygonoptions.fillColor(Color.BLUE);
//          polygon = myMap.addpolygon(polygonoptions);
//      }else{
//          if(polygon != null){
//              polygon.remove();
//              polygon = null;
//          }
//          
//          polygonoptions = new polygonoptions().add(marker.getPosition());
//          markerClicked = true;
//      }
//      
//      return true;
//  }

}

解决方法

一种方法可以是通过地图创建一个视图,并为此视图创建一个OnTouchListener来拦截地图触摸:

activity_maps.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="match_parent"
                android:layout_height="match_parent">

    <fragment
        android:id="@+id/map"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:name="com.google.android.gms.maps.SupportMapFragment" />

    <View
        android:id="@+id/draggable"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:clickable="true" />

</RelativeLayout>

MapsActivity.java

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
    private GoogleMap mMap;
    private View draggableView;
    private List<LatLng> polylinePoints = new ArrayList<>();
    private polyline polyline;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);

        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

        draggableView = findViewById(R.id.draggable);
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        draggableView.setonTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view,MotionEvent motionEvent) {
                LatLng position = mMap.getProjection().fromScreenLocation(
                        new Point((int) motionEvent.getX(),(int) motionEvent.getY()));

                if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
                    if (polyline != null) {
                        polyline.remove();
                        polyline = null;
                    }
                    polyline = mMap.addpolyline(
                            new polylineoptions().color(Color.RED).addAll(polylinePoints));
                } else if (motionEvent.getAction() == MotionEvent.ACTION_MOVE){
                    polylinePoints.add(position);
                    polyline.setPoints(polylinePoints);
                } else if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
                    // Close the polyline?
                }
                return true;
            }
        });
    }
}

java – 用手指在Google地图上自由绘制的更多相关文章

  1. html5 canvas合成海报所遇问题及解决方案总结

    这篇文章主要介绍了html5 canvas合成海报所遇问题及解决方案总结,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

  2. Html5 video标签视频的最佳实践

    这篇文章主要介绍了Html5 video标签视频的最佳实践,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

  3. HTML5地理定位_动力节点Java学院整理

    地理位置(Geolocation)是 HTML5 的重要特性之一,提供了确定用户位置的功能,借助这个特性能够开发基于位置信息的应用。今天这篇文章向大家介绍一下 HTML5 地理位置定位的基本原理及各个浏览器的数据精度情况

  4. HTML5在微信内置浏览器下右上角菜单的调整字体导致页面显示错乱的问题

    HTML5在微信内置浏览器下,在右上角菜单的调整字体导致页面显示错乱的问题,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧

  5. ios – containerURLForSecurityApplicationGroupIdentifier:在iPhone和Watch模拟器上给出不同的结果

    我使用默认的XCode模板创建了一个WatchKit应用程序.我向iOSTarget,WatchkitAppTarget和WatchkitAppExtensionTarget添加了应用程序组权利.(这是应用程序组名称:group.com.lombax.fiveminutes)然后,我尝试使用iOSApp和WatchKitExtension访问共享文件夹URL:延期:iOS应用:但是,测试NSURL

  6. 适用于iOS和路线的Google Maps SDK

    解决方法库中有一些东西不在文档中,所以如果你正在寻找一个功能,那么值得下载SDK并查看标题.然而,在当前版本1.0.2中,我没有看到任何路由–搜索路线或绘制路线.目前,您唯一的选择可能是使用其他GoogleApi来查找路径,然后正如Lee所说,使用折线绘制它们.

  7. Ionic – Splash Screen适用于iOS,但不适用于Android

    我有一个离子应用程序,其中使用CLI命令离子资源生成的启动画面和图标iOS版本与正在渲染的启动画面完美配合,但在Android版本中,只有在加载应用程序时才会显示白屏.我检查了config.xml文件,所有路径看起来都是正确的,生成的图像出现在相应的文件夹中.(我使用了splash.psd模板来生成它们.我错过了什么?这是config.xml文件供参考,我觉得我在这里做错了–解决方法在config.xml中添加以下键:它对我有用!

  8. ios – 无法启动iPhone模拟器

    /Library/Developer/CoreSimulator/Devices/530A44CB-5978-4926-9E91-E9DBD5BFB105/data/Containers/Bundle/Application/07612A5C-659D-4C04-ACD3-D211D2830E17/ProductName.app/ProductName然后,如果您在Xcode构建设置中选择标准体系结构并再次构建和运行,则会产生以下结果:dyld:lazysymbolbindingFailed:Symbol

  9. 适用于iOS的Google Maps SDK不断增加内存使用量

    我已经构建了一个在地图上显示标记的简单应用程序,我从服务器的JSON文件加载其x,y,标记是可点击的,所以一旦你在任何标记上它将你带到另一个UIViewController(我们将它命名为BViewController).我已经监视了内存使用情况,所以每次我从BViewController返回到MapViewController(里面的地图)时,它只是内存使用量的两倍我尝试将其设置为nill或从s

  10. 通过cocoapods安装适用于iOS的Google Maps SDK会导致链接器错误

    我正在尝试使用cocoapods安装适用于iOS版本1.3.0的GoogleMapsSDK.实际上安装过程很成功,但是当我尝试使用框架时,app构建过程会返回链接器错误,例如:由于某种原因,链接器无法找到框架.我的cocoapods版本是0.20.1.XCode4.6.2.除了谷歌地图SDK,我的项目还有另外两个通过cocoapods添加的库.这是我的Podfile:提前致谢.解决方法您应该看到一个文件“Pods.xcconfig”,其中包含pod正在使用的框架.将应用程序的目标配置更改为基于CocoaP

随机推荐

  1. 基于EJB技术的商务预订系统的开发

    用EJB结构开发的应用程序是可伸缩的、事务型的、多用户安全的。总的来说,EJB是一个组件事务监控的标准服务器端的组件模型。基于EJB技术的系统结构模型EJB结构是一个服务端组件结构,是一个层次性结构,其结构模型如图1所示。图2:商务预订系统的构架EntityBean是为了现实世界的对象建造的模型,这些对象通常是数据库的一些持久记录。

  2. Java利用POI实现导入导出Excel表格

    这篇文章主要为大家详细介绍了Java利用POI实现导入导出Excel表格,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

  3. Mybatis分页插件PageHelper手写实现示例

    这篇文章主要为大家介绍了Mybatis分页插件PageHelper手写实现示例,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪

  4. (jsp/html)网页上嵌入播放器(常用播放器代码整理)

    网页上嵌入播放器,只要在HTML上添加以上代码就OK了,下面整理了一些常用的播放器代码,总有一款适合你,感兴趣的朋友可以参考下哈,希望对你有所帮助

  5. Java 阻塞队列BlockingQueue详解

    本文详细介绍了BlockingQueue家庭中的所有成员,包括他们各自的功能以及常见使用场景,通过实例代码介绍了Java 阻塞队列BlockingQueue的相关知识,需要的朋友可以参考下

  6. Java异常Exception详细讲解

    异常就是不正常,比如当我们身体出现了异常我们会根据身体情况选择喝开水、吃药、看病、等 异常处理方法。 java异常处理机制是我们java语言使用异常处理机制为程序提供了错误处理的能力,程序出现的错误,程序可以安全的退出,以保证程序正常的运行等

  7. Java Bean 作用域及它的几种类型介绍

    这篇文章主要介绍了Java Bean作用域及它的几种类型介绍,Spring框架作为一个管理Bean的IoC容器,那么Bean自然是Spring中的重要资源了,那Bean的作用域又是什么,接下来我们一起进入文章详细学习吧

  8. 面试突击之跨域问题的解决方案详解

    跨域问题本质是浏览器的一种保护机制,它的初衷是为了保证用户的安全,防止恶意网站窃取数据。那怎么解决这个问题呢?接下来我们一起来看

  9. Mybatis-Plus接口BaseMapper与Services使用详解

    这篇文章主要为大家介绍了Mybatis-Plus接口BaseMapper与Services使用详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪

  10. mybatis-plus雪花算法增强idworker的实现

    今天聊聊在mybatis-plus中引入分布式ID生成框架idworker,进一步增强实现生成分布式唯一ID,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

返回
顶部