精华内容
下载资源
问答
  • osmdroid
    2021-04-27 17:42:40

    http://osmdroid.github.io/osmdroid/

    osmdroid is a (almost) full/free replacement for Android's MapView (v1 API) class. It also includes a modular tile provider system with support for numerous online and offline tile sources and overlay support with built-in overlays for plotting icons, tracking location, and drawing shapes.

    osmdroid是Android的MapView类的完全/免费的替代品。它还包括一个模块化的切片供应系统,支持大量的在线和离线切片来源,以及overlay支持,内置绘制图标,跟踪位置,并绘制形状的叠加操作。

    Non-Maven, Non-Gradle users

    If you are not yet using Maven or Gradle, you can include osmdroid by downloading directly from Maven Central.

    如果你还没有使用过Maven或者Gradle,你可以离线下载然后包含进来。

    You have a choice between using an AAR (for >=5.0) or JAR (for < 4.3) in your libs folder.

    For versions < 4.3, you also need slf4j-api and slf4j-android.

    Version >= v5.0

    If you're still using Eclipse without a backing building system (maven/gradle), you'll probably want to google around on how to use AAR files with Eclipse. By now, most people have probably moved on to Android Studio with gradle, since it's really the only supported solution. Some users have reported success by unzipping the AAR and the classes jar files and then including them in the classpath.

    如果你仍然在使用Eclipse,不能使用aar文件,因为aar文件只有Android Studio才能调用。那么怎么调用最新的osmdroid.jar包呢?有人发现可以这样做,解压aar,把其中的classes.jar包复制到你的libs目录下。

    Good luck!

    祝你好运!

    "Hello osmdroid World"

    osmdroid's MapView is basically a replacement for Google's MapView class. First of all, create your Android project, and follow HowToMaven if you're using Maven, or follow HowToGradle if you're using Gradle/Android Studio. This will help you get the binaries for osmdroid included in your project.

    Manifest

    In most cases, you will have to set the following authorizations in your AndroidManifest.xml:

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"  />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    

    If you are only using parts of the library, you can adjust the permissions accordingly.

    Online tile provider

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"  />
    

    Offline tile provider and storing tiles

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    

    Location provider

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

    Android 6.0+ devices require you have to check for "dangerous" permissions at runtime.
    osmdroid requires the following dangerous permissions:
    WRITE_EXTERNAL_STORAGE and ACCESS_COARSE_LOCATION/ACCESS_FINE_LOCATION.
    See OpenStreetMapViewer's implementation or Google Documentation on Permissions

    Layout

    Create a "src/main/res/layouts/main.xml" layout like this one. With Android Studio, it probably created one already. The default is called "src/main/res/layouts/activity_main.xml":

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:orientation="vertical" 
            android:layout_width="fill_parent"
            android:layout_height="fill_parent">
            <org.osmdroid.views.MapView android:id="@+id/map"
                    android:layout_width="fill_parent" 
                    android:layout_height="fill_parent" />
    </LinearLayout>
    

    Main Activity

    We now create the main activity (MainActivity.java):

    import org.osmdroid.tileprovider.tilesource.TileSourceFactory;
    import org.osmdroid.views.MapView;
    
    public class MainActivity extends Activity {
        MapView map = null;
        @Override public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            //handle permissions first, before map is created. not depicted here
    
            //load/initialize the osmdroid configuration, this can be done 
            Context ctx = getApplicationContext();
            Configuration.getInstance().load(ctx, PreferenceManager.getDefaultSharedPreferences(ctx));
            //setting this before the layout is inflated is a good idea
            //it 'should' ensure that the map has a writable location for the map cache, even without permissions
            //if no tiles are displayed, you can try overriding the cache path using Configuration.getInstance().setCachePath
            //see also StorageUtils
            //note, the load method also sets the HTTP User Agent to your application's package name, abusing osm's tile servers will get you banned based on this string
    
            //inflate and create the map
            setContentView(R.layout.activity_main);
    
            map = (MapView) findViewById(R.id.map);
            map.setTileSource(TileSourceFactory.MAPNIK);
        }
    
        public void onResume(){
            super.onResume();
            //this will refresh the osmdroid configuration on resuming.
            //if you make changes to the configuration, use 
            //SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
            //Configuration.getInstance().load(this, PreferenceManager.getDefaultSharedPreferences(this));
            map.onResume(); //needed for compass, my location overlays, v6.0.0 and up
        }
    
        public void onPause(){
            super.onPause();
            //this will refresh the osmdroid configuration on resuming.
            //if you make changes to the configuration, use 
            //SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
            //Configuration.getInstance().save(this, prefs);
            map.onPause();  //needed for compass, my location overlays, v6.0.0 and up
        }
    }
    

    And that's enough to give it a try, and see the world map.

    Then we add default zoom buttons, and ability to zoom with 2 fingers (multi-touch)

            map.setBuiltInZoomControls(true);
            map.setMultiTouchControls(true);
    

    We can move the map on a default view point. For this, we need access to the map controller:

            IMapController mapController = map.getController();
            mapController.setZoom(9.5);
            GeoPoint startPoint = new GeoPoint(48.8583, 2.2944);
            mapController.setCenter(startPoint);
    

    Advanced tutorial

    The best example of how to use the osmdroid library is our OpenStreetMapViewer sample project. It contains a basic osmdroid application plus a few special-use examples. It is recommended you use this project as an example for building your application.

    Adding a MapView

    You can add a MapView to your xml layout using:

    <org.osmdroid.views.MapView
        android:id="@+id/mapview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tilesource="Mapnik" />
    

    This will allow you to configure the tile source imagery for your MapView but not much else.

    However, for more control over your MapView, you will want to create a MapView programmatically.

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mMapView = new MapView(inflater.getContext(), 256, getContext());
        return mMapView;
    }
    

    Images for Buttons and whatnot

    For osmdroid 4.3 and older, there's a number of resources that the map uses for various user interface helpers, such as zoom in/out buttons, the device's current location when GPS is available and more. These resources are loaded via the "ResourceProxy". The idea is that you can either bring your own images or borrow the ones from osmdroid. If you're borrowing, then you'll want to grab the files located here and add them to your project "src/main/res/drawable".

    For osmdroid 5.0 and 5.1, the drawables are included with the AAR package. The resource proxy is still present and used so you can override values and images as needed.

    For osmdroid 5.2 and up, the resource proxy is removed from the API set and replaced with Android context.

    Create a custom Resource Proxy

    Applies only to versions prior to 5.2

    As mentioned above, the Resource Proxy is a bit of a strange animal that osmdroid uses to load some images for user interface controls. If you're using any of the built-in controls that need images (zoom in/out, person icon, etc) you'll either need to provide your own images, borrow the images from osmdroid's example app, or provide your own implementation of Resource Proxy.

    The example osmdroid app includes an example of this called CustomResourceProxy (included with > 4.3 osmdroid). All it does is change the my location drawable (person) to an alternate image. The example is below.

    public class CustomResourceProxy extends DefaultResourceProxyImpl {
    
         private final Context mContext;
         public CustomResourceProxy(Context pContext) {
              super(pContext);
    		mContext = pContext;
         }
         
         @Override
    	public Bitmap getBitmap(final bitmap pResId) {
    		switch (pResId){
                   case person:
                        //your image goes here!!!
                        return BitmapFactory.decodeResource(mContext.getResources(),org.osmdroid.example.R.drawable.sfgpuci);
              }
              return super.getBitmap(pResId);
    	}
    
    	@Override
    	public Drawable getDrawable(final bitmap pResId) {
    		switch (pResId){
                   case person:
                        return mContext.getResources().getDrawable(org.osmdroid.example.R.drawable.sfgpuci);
              }
              return super.getDrawable(pResId);
    	}
    }
    

    Then you can use your instance using the following snippet.

    mResourceProxy = new CustomResourceProxy(getApplicationContext());
    final RelativeLayout rl = new RelativeLayout(this);
    this.mOsmv = new MapView(this,mResourceProxy);
    

    In order to see any difference with our example (changes the person icon), we'll need to get a location fix and add it to the map layers.

    this.mLocationOverlay = new MyLocationNewOverlay(new GpsMyLocationProvider(this), mOsmv, mResourceProxy);
    this.mLocationOverlay.enableMyLocation();
    this.mOsmv.getOverlays().add(mLocationOverlay);
    this.mOsmv.setMultiTouchControls(true);
    

    Map Overlays

    How to add the My Location overlay

    Note: you need manifest Fine Location permissions and if you are targeting API23+ APIs, you have to ask the user to explicitly grant location runtime permissions.

    Notice: this is a very simple example that does not handle android lifecycle correctly. Versions 5.6.5 and older, you'll need to handle automatically disabling/enabling the location provider with android life cycle events. Version 6.0.0, this is handled so long as you call map view onPause and onResume appropriately.

    this.mLocationOverlay = new MyLocationNewOverlay(new GpsMyLocationProvider(context),mMapView);
    this.mLocationOverlay.enableMyLocation();
    mMapView.getOverlays().add(this.mLocationOverlay);
    

    How to add a compass overlay

    Notice: this is a very simple example that does not handle android lifecycle correctly. Versions 5.6.5 and older, you'll need to handle automatically disabling/enabling the compass/orientation provider with android life cycle events. Version 6.0.0, this is handled so long as you call map view onPause and onResume appropriately.

    this.mCompassOverlay = new CompassOverlay(context, new InternalCompassOrientationProvider(context), mMapView);
    this.mCompassOverlay.enableCompass();
    mMapView.getOverlays().add(this.mCompassOverlay);
    

    How to enable the Grid line Overlay

    Useful for displaying latitude/longitude grid lines.

    v5.2 up to v5.6.5, see the sample app's source code from those tagged versions.

    v6.0.0 and up

    LatLonGridlineOverlay2 overlay = new LatLonGridlineOverlay2();
    mMapView.getOverlays().add(overlay);
    

    How to enable rotation gestures

    mRotationGestureOverlay = new RotationGestureOverlay(context, mMapView);
    mRotationGestureOverlay.setEnabled(true);
    mMapView.setMultiTouchControls(true);
    mMapView.getOverlays().add(this.mRotationGestureOverlay);
    

    How to add Map Scale bar overlay

    final Context context = this.getActivity();
    final DisplayMetrics dm = context.getResources().getDisplayMetrics();
    mScaleBarOverlay = new ScaleBarOverlay(mMapView);
    mScaleBarOverlay.setCentred(true);
    //play around with these values to get the location on screen in the right place for your application
    mScaleBarOverlay.setScaleBarOffset(dm.widthPixels / 2, 10);
    mMapView.getOverlays().add(this.mScaleBarOverlay);
    

    How to add the built-in Minimap

    Note: do not use when rotation is enabled! (Keep reading for a work around)

    mMinimapOverlay = new MinimapOverlay(context, mMapView.getTileRequestCompleteHandler());
    mMinimapOverlay.setWidth(dm.widthPixels / 5);
    mMinimapOverlay.setHeight(dm.heightPixels / 5);
    //optionally, you can set the minimap to a different tile source
    //mMinimapOverlay.setTileSource(....);
    mMapView.getOverlays().add(this.mMinimapOverlay);
    

    Versions 5.6.5 and older: If you want the minimap to stay put when rotation is enabled, create a second map view in your layout file, then wire up a change listener on the main map and use that to set the location on the minimap. For the reverse, you need to do the same process, however, you have to filter map motion events to prevent infinite looping. There's an example on how to sync the views within the example application.

    Version 6.0.0: the above tip is no longer necessary.

    How do I place icons on the map with a click listener?

    //your items
    ArrayList<OverlayItem> items = new ArrayList<OverlayItem>();
    items.add(new OverlayItem("Title", "Description", new GeoPoint(0.0d,0.0d))); // Lat/Lon decimal degrees
    
    //the overlay
    ItemizedOverlayWithFocus<OverlayItem> mOverlay = new ItemizedOverlayWithFocus<OverlayItem>(items,
    	new ItemizedIconOverlay.OnItemGestureListener<OverlayItem>() {
    	@Override
    	public boolean onItemSingleTapUp(final int index, final OverlayItem item) {
    	//do something
    	    return true;
    	}
    	@Override
    	public boolean onItemLongPress(final int index, final OverlayItem item) {
    		return false;
    	}
    }, context);
    mOverlay.setFocusItemsOnTap(true);
    
    mMapView.getOverlays().add(mOverlay);
    

    How many icons can I put on the map?

    The answer is greatly dependent on what hardware the osmdroid based app is running on. A Samsung S5 (no endorsement intended) ran just fine at 3k icons and was noticeably choppy at 6k icons. Your mileage may vary. X86 Android running on modern hardware will perform great at even higher numbers. However, it's recommended to limit the amount of stuff you're rendering, if at all possible.

    If you're also drawing paths, lines, polygons, etc, then this also changes the equation. Drawing multipoint graphics is computationally more expensive and thus negatively affects performance under higher loads. To mitigate performance issues with multipoint graphics, one strategy would be to reduce the number of points handed off to the map engine when at a higher zoom level (numerically lower), then increase the fidelity as the user zoom's in. In effect, you would be clipping the visible data at the map view bounds so that the map view only "knows" about what's on screen and doesn't have to loop through all 10k icons that you want on the map. Although you can give the map view all 10k objects, but every time the map moves or zooms, it will iterate over all 10k items to calculate where to draw them (if at all). Using this mechanism paired with map motion listeners and a database query that supports geographic bounds, you can support a rich experience for users with lots of data and still have reasonable performance.

    Reusing drawables for icons will help with memory usage too.

    Map Sources, Imagery and Tile sets.

    See https://github.com/osmdroid/osmdroid/wiki/Map-Sources

    Using osmdroid in a recycler view

    Applies to: v5.6.5 and older. (v6.0.0 has this fix applied already)

    It has been brought up a view times that osmdroid's MapView does not play nicely in a RecyclerView. The MapView is a custom android ViewGroup that implements the necessary API calls that ViewGroup requires, namely onDetachedFromWindow. In this function call, osmdroid basically calls destructors on all associated overlays, threading, tile loading, etc. This is destructive and cannot be reinitialized. This was done primarily to prevent memory leaks. Since ViewGroup does not have a destroy method or anything else that happens during garbage collection, this is really the only place we can put clean up code. As such, using the map in a recycler view won't work without this simple one liner.

        if (Build.VERSION.SDK_INT >= 16)
    	mapView.setHasTransientState(true);
    

    Now naturally, this will only function on devices at API16 (Jelly Bean) and newer so the recommendation is to simply not use osmdroid in a recycler view for older APIs. The alternative approach is for you to extend the MapView and override the method for public void onDetach() and simply provide an empty body. This will create memory leaks though so use with caution.

    Related tickets:

     

    http://osmdroid.github.io/osmdroid/

    更多相关内容
  • osmdroid地图

    2018-04-20 14:40:09
    不想用百度地图sdk?可以尝试一下国外的开源osmdroid
  • osmdroid基础符号化.zip

    2020-07-16 14:52:43
    开源地图osmdroid的基础符号化,包括文字、点线的符号化的基础示例。可以设置点的显示图片,线条的可以符号化为虚线、实现等。
  • osmdroid-演示 osmdroid 演示应用程序
  • osmdroid离线sqlite文件

    2017-08-31 15:34:54
    这是个从MOBAC自己抓取的osmdroid可以使用的sqlite格式离线文件,用于测试学习osmdroid离线地图使用 欢迎大家下载
  • osmdroid是(几乎)完全/免费的Android的MapView(v1 API)类的替代品。 它还包括一个模块化的图块提供程序系统,该系统提供对众多在线和离线图块源的支持,并通过内置的覆盖图(用于绘制图标,跟踪位置和绘制形状...
  • NULL 博文链接:https://topmanopensource.iteye.com/blog/1637317
  • osmdroid 加载geopackage离线底图。还有之前测试的osmdroid常用知识。我的博客网址:http://blog.csdn.net/qq_16064871
  • android 开源库osmdroid绘制点线面(比例尺,缩小放大,导航图标等)。常用的基本用法都有,以及之前写加载离线地图也在这个项目。 我的博客地址:http://blog.csdn.net/qq_16064871。
  • osmdroid, Android工具.zip

    2019-10-10 08:27:25
    osmdroid, Android工具 osmdroidosmdroid是一个( 几乎) 完整/免费的,用于 android ( v1 API ) 类的MapView 。 它还包括一个模块化的平铺提供商系统,支持大量在线和脱机瓦。当前版本:5.6.
  • 特点和问题:// Todo文章:GC,Java内存模型,内存泄漏屏幕截图:
  • osmdroid离线sqlite格式地图资源,北京市,可以直接离线加载,已测试 请放心下载
  • osmdroid作为一个开源的项目,在在线地图上还是做的不错,离线地图上也能支持多种格式,例如:zip,sqlite,.mbtiles,gemf,map,gpkg等格式。就是不能直接加载shp文件大为苦恼。osmdroid没有可以设置坐标参考系的...
  • osmdroid-android-6.1.0.aar

    2019-07-22 14:55:22
    设计用于完全替换 Android 内部的 MapView 类,包含一个模块化的地图拼图,支持在线和离线地图以及覆盖地图,支持标注图标、位置跟踪和绘制形状。地图引擎使用 OpenStreetMap
  • OSMDroidApps 使用 osmdroid 打开街道地图 Android 应用程序
  • osmdroid-android-3.0.9.zip

    2019-10-21 16:40:01
    JsonPath.zip,纯java jsonpath实现jsonpath规范的java实现
  • osmdroid官方源码

    2016-11-22 11:40:44
    osmdroid官方源码,源码的介绍参考文章http://blog.csdn.net/qq_30124547/article/details/53266136
  • Osmdroid示例APK

    2016-11-21 22:15:28
    Sample---osmdroid-5.5.zip,Sample---osmdroid-5.5,OpenStreetMapViewer-5.5-release.apk,osmdroid-android-5.5-debug-javadoc.jar,osmdroid-third-party-5.5-debug.aar,osmdroid-mapsforge-5.5-release-javadoc.jar...
  • osmdroid 源码

    2016-01-02 13:23:46
    osmdroid-master android 手机端的地图应用
  • osmdroid 5.6.3版本jar包

    2017-08-30 16:58:31
    osmdroid官网迁移到github后更新都是arr包 所以4.2以后资源多是arr 我的是从arr中提取出来的
  • android osmdroid离线加载常用格式zip,sqlite,.mbtiles,gemf。也可以在线加载地图。osmdroid的github地址:https://github.com/osmdroid/osmdroid;我的博客地址:http://blog.csdn.net/qq_16064871。
  • osmdroid-third-party-4.0.zip

    2019-10-14 07:51:21
    notfound-webview.zip,这是一个帮助寻找失踪儿童的项目。这是一个帮助寻找失踪儿童的项目。
  • Osmdroid源码

    2015-04-27 10:55:34
    Osmdroid源码,对于有要深入研究osmdroid引擎源码的朋友使用。代码组织格式为Eclipse;
  • android 使用osmdroid 加载离线map格式数据以及地图网格。我的博客地址:http://blog.csdn.net/qq_16064871。
  • osmdroid 新手入门

    2020-08-02 16:01:34
    文章目录前言osmdroid简介实现效果图实现步骤源码包参考文献 前言 闲着无聊,安装了Android Studio 回忆一下Android开发,当打开Android Studio时,那种熟悉的感觉又回来了。之前了解到 osmdroid 的功能很强大,于是...

    前言

    闲着无聊,安装了Android Studio 回忆一下Android开发,当打开Android Studio时,那种熟悉的感觉又回来了。之前了解到 osmdroid 的功能很强大,于是就想尝试一下。希望本文可以给想学习的小白提供一些参考。

    osmdroid简介

    osmdroid 是(几乎)完全/免费的Android的MapView(v1 API)类的替代品。 它还包括一个模块化的图块提供程序系统,该系统提供对许多在线和离线图块源的支持,并通过内置的覆盖图(用于绘制图标,跟踪位置和绘制形状)来支持覆盖图。

    实现效果图

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-JMS2fRWZ-1596354708682)(./images/osmdroid.png)]

    实现步骤

    1. 使用 Android Studio 新建一个带 Basic Activity 的项目模板,点击 Next
      在这里插入图片描述

    2. 设置项目名、包名、项目路径、开发语言、支持的最小SDK。然后点击 Finish
      在这里插入图片描述

    3. 项目结构
      在这里插入图片描述

    4. 添加阿里依赖仓库(顺便解决 gradle 构建缓慢的问题)
      在这里插入图片描述

      // Top-level build file where you can add configuration options common to all sub-projects/modules.
      buildscript {
          repositories {
              maven {
                  url 'https://maven.aliyun.com/repository/public/'
              }
              mavenLocal()
              mavenCentral()
              google()
              jcenter()
          }
          dependencies {
              classpath "com.android.tools.build:gradle:4.0.1"
      
              // NOTE: Do not place your application dependencies here; they belong
              // in the individual module build.gradle files
          }
      }
      
      allprojects {
          repositories {
              maven {
                  url 'https://maven.aliyun.com/repository/public/'
              }
              mavenLocal()
              mavenCentral()
              google()
              jcenter()
          }
      }
      
      task clean(type: Delete) {
          delete rootProject.buildDir
      }
      

    提 示 : \color{orange}{提示:} 添加 maven 配置后 点击 Sync Now 同步

    1. 添加 osmdroid 函数库
      在这里插入图片描述

      implementation 'org.osmdroid:osmdroid-android:6.1.8'
      
    2. AndroidManifest.xml 中添加权限
      在这里插入图片描述

      <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
      <uses-permission android:name="android.permission.INTERNET" />
      <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"  />
      <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
      
    3. 添加布局 (layout)
      在这里插入图片描述

      <?xml version="1.0" encoding="utf-8"?>
      <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
          xmlns:app="http://schemas.android.com/apk/res-auto"
          xmlns:tools="http://schemas.android.com/tools"
          android:orientation="vertical"
          android:layout_width="fill_parent"
          android:layout_height="fill_parent"
          tools:context=".FirstFragment">
      
          <org.osmdroid.views.MapView android:id="@+id/map"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent"
              tools:ignore="MissingConstraints" />
      </androidx.constraintlayout.widget.ConstraintLayout>
      
    4. 修改 Activity

      package com.example.myapplication;
      
      import android.Manifest;
      import android.content.Context;
      import android.content.pm.PackageManager;
      import android.os.Bundle;
      import android.preference.PreferenceManager;
      import android.view.LayoutInflater;
      import android.view.View;
      import android.view.ViewGroup;
      
      import androidx.annotation.NonNull;
      import androidx.core.app.ActivityCompat;
      import androidx.core.content.ContextCompat;
      import androidx.fragment.app.Fragment;
      import androidx.navigation.fragment.NavHostFragment;
      
      import org.osmdroid.api.IMapController;
      import org.osmdroid.config.Configuration;
      import org.osmdroid.tileprovider.tilesource.TileSourceFactory;
      import org.osmdroid.util.GeoPoint;
      import org.osmdroid.views.MapView;
      
      import java.util.ArrayList;
      
      public class FirstFragment extends Fragment {
      
          private final int REQUEST_PERMISSIONS_REQUEST_CODE = 1;
          private MapView map = null;
      
          @Override
          public View onCreateView(
                  LayoutInflater inflater, ViewGroup container,
                  Bundle savedInstanceState
          ) {
              // Inflate the layout for this fragment
              return inflater.inflate(R.layout.fragment_first, container, false);
          }
      
          @Override
          public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
              super.onViewCreated(view, savedInstanceState);
      
              //handle permissions first, before map is created. not depicted here
      
              //load/initialize the osmdroid configuration, this can be done
              Context ctx = getContext();
              Configuration.getInstance().load(ctx, PreferenceManager.getDefaultSharedPreferences(ctx));
              //setting this before the layout is inflated is a good idea
              //it 'should' ensure that the map has a writable location for the map cache, even without permissions
              //if no tiles are displayed, you can try overriding the cache path using Configuration.getInstance().setCachePath
              //see also StorageUtils
              //note, the load method also sets the HTTP User Agent to your application's package name, abusing osm's
              //tile servers will get you banned based on this string
      
              //inflate and create the map
              setTargetFragment(this.getTargetFragment(), REQUEST_PERMISSIONS_REQUEST_CODE);
      
              map = (MapView) view.findViewById(R.id.map);
              map.setTileSource(TileSourceFactory.MAPNIK);
              map.setBuiltInZoomControls(true);
              map.setMultiTouchControls(true);
              IMapController mapController = map.getController();
              mapController.setZoom(9.5);
              GeoPoint startPoint = new GeoPoint(48.8583, 2.2944);
              mapController.setCenter(startPoint);
      
              requestPermissionsIfNecessary(new String[] {
                      // if you need to show the current location, uncomment the line below
                      // Manifest.permission.ACCESS_FINE_LOCATION,
                      // WRITE_EXTERNAL_STORAGE is required in order to show the map
                      Manifest.permission.WRITE_EXTERNAL_STORAGE
              });
          }
      
          @Override
          public void onResume() {
              super.onResume();
              //this will refresh the osmdroid configuration on resuming.
              //if you make changes to the configuration, use
              //SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
              //Configuration.getInstance().load(this, PreferenceManager.getDefaultSharedPreferences(this));
              map.onResume(); //needed for compass, my location overlays, v6.0.0 and up
          }
      
          @Override
          public void onPause() {
              super.onPause();
              //this will refresh the osmdroid configuration on resuming.
              //if you make changes to the configuration, use
              //SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
              //Configuration.getInstance().save(this, prefs);
              map.onPause();  //needed for compass, my location overlays, v6.0.0 and up
          }
      
          @Override
          public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
              ArrayList<String> permissionsToRequest = new ArrayList<>();
              for (int i = 0; i < grantResults.length; i++) {
                  permissionsToRequest.add(permissions[i]);
              }
              if (permissionsToRequest.size() > 0) {
                  ActivityCompat.requestPermissions(
                          this.getActivity(),
                          permissionsToRequest.toArray(new String[0]),
                          REQUEST_PERMISSIONS_REQUEST_CODE);
              }
          }
      
          private void requestPermissionsIfNecessary(String[] permissions) {
              ArrayList<String> permissionsToRequest = new ArrayList<>();
              for (String permission : permissions) {
                  if (ContextCompat.checkSelfPermission(this.getActivity(), permission)
                          != PackageManager.PERMISSION_GRANTED) {
                      // Permission is not granted
                      permissionsToRequest.add(permission);
                  }
              }
              if (permissionsToRequest.size() > 0) {
                  ActivityCompat.requestPermissions(
                          this.getActivity(),
                          permissionsToRequest.toArray(new String[0]),
                          REQUEST_PERMISSIONS_REQUEST_CODE);
              }
          }
      }
      

    源码包

    源码已审核通过,点击这里下载!

    参考文献

    osmdroid github上的源码 点击这里获取源码
    osmdroid gitee上的源码 点击这里快速获取源码
    阿里云仓库

    展开全文
  • osmdroid is a (almost) full/free replacement for Android's MapView (v1 API) class. It also includes a modular tile provider system with support for numerous online and offline tile sources and overlay...

    osmdroid is a (almost) full/free replacement for Android's MapView (v1 API) class. It also includes a modular tile provider system with support for numerous online and offline tile sources and overlay support with built-in overlays for plotting icons, tracking location, and drawing shapes.

    Current Release: 6.1.10 Jan 30, 2021

    Current Development version: 6.1.11-SNAPSHOT

    Next Release Version (planned): 6.1.11

    Note: check your calendar, it may take up to a few days for all global mirrors to update.

    Please read the osmdroid wiki for tutorials on integration.

    Gradle dependency

    repositories {
            mavenCentral()
    }
    
    dependencies {
        compile 'org.osmdroid:osmdroid-android:<VERSION>'
    }

    Be sure to replace <VERSION> with the last release version above.

    Maven dependency

    <dependency>
      <groupId>org.osmdroid</groupId>
      <artifactId>osmdroid-android</artifactId>
      <version><VERSION></version>
      <type>aar</type>
    </dependency>

    Platform or API Level (API level 8 = Platform 2.2)

    <platform>8</platform>

    You can also compile osmdroid from source or download the dependency directly from OSS or download the distribution package

    Want the latest and greatest?

    We periodically publish snapshots to maven central. If you're interesting in trying it out, using the following:

    repositories {
        mavenCentral()
        maven{
            url  'https://oss.sonatype.org/content/repositories/snapshots/'
            name 'OSS-Sonatype'
        }
    }
    dependencies {
        compile 'org.osmdroid:osmdroid-android:<VERSION>-SNAPSHOT:debug@aar'
    }

    Use at your own risk though, it may not be stable or may have bugs or performance issues. If you run across any, please report them.

    In case gradle doesn't resolve it, it can be download manually here: https://oss.sonatype.org/service/local/repositories/snapshots/content/org/osmdroid/osmdroid-android/-SNAPSHOT/osmdroid-android--SNAPSHOT.aar

    Side note: gradle's cached dependencies and doesn't really handle snapshot very well. To force gradle to update snapshots on every build, try adding this to your root build.gradle file.

    allprojects  {
      // forces all changing dependencies (i.e. SNAPSHOTs) to automagicially download
        configurations.all {
            resolutionStrategy {
                cacheChangingModulesFor 0, 'seconds'
        }
    }

    You can also build your project using the gradle option --refreshDependencies

    OK now what?

    Continue reading here, How-to-use-the-osmdroid-library

    Related and important wiki articles

    I have a question or want to report a bug

    If you have a question, please view the osmdroid FAQ.
    You can also view the Stack Overflow osmdroid tag and osmdroid Google Group where you can get feedback from a large pool of osmdroid users.

    If you still have an issue, please check the Changelog page to see if this issue is fixed in a newer or upcoming version of osmdroid.

    If think you have a legitimate bug to report then go to the Issues page to see if your issue has been reported. If your issue already exists then please contribute information that will help us track down the source of the issue. If your issue does not exist then create a new issue report. When creating an issue, please include the version of osmdroid, the Android platform target and test device you are using, and a detailed description of the problem with relevant code. It is particularly helpful if you can reproduce the problem using our OpenStreetMapViewer sample project as your starting point.

    I want to contribute

    See our contributing guide

    For your reference, the dashboard provides a high level overview of the repository including structure of UI classesmodule dependenciesexternal libraries, and other components of the system.

    I want more!

    The OSMBonusPack project adds additional functionality for use with osmdroid projects.

    Screenshots

      

    Demo Videos

    Free Draw

    Maps Forge

    Floating point zoom

    IIS Tracker

    Building from source and using the aar in your app

    Thanks to Gradle Fury, this publishes the artifacts to mavenLocal.

    ./gradlew clean install
    

    In your root build.gradle file, add mavenLocal() if not present.

    allprojects {
        repositories {
                mavenCentral()
                mavenLocal()    //add this if it's missing
        }
    }
    
    

    Then in your APK or AAR project that needs osmdroid.

        compile 'org.osmdroid:osmdroid-android:<VERSION>-SNAPSHOT:debug@aar'
    

    Where VERSION is the version listed as the value for pom.version in gradle.properties. Note that when using the release versions from Maven Central, drop the :debug@aar part. When using a "release" version that you build locally with gradle, you'll need :debug@aar instead.

    https://github.com/osmdroid/osmdroid

    https://blog.csdn.net/robotskly/article/details/104092028?spm=1001.2014.3001.5501

    >>Android Map, Google Map, Baidu Map, AMap, and so on.

    首先,打开osmdroid-master

    这个大project,有很多小project组成。。。那么应该打开哪一个呢?

    How to use the osmdroid library (Kotlin)

    EditNew Page

    IpswichMapper edited this page 22 days ago · 5 revisions


    "Hello osmdroid World"

    This page is a kotlin adaptation of the original page. It is incomplete.

    osmdroid's MapView is basically a replacement for Google's MapView class. First of all, create your Android project, and follow HowToMaven if you're using Maven, or follow HowToGradle if you're using Gradle/Android Studio. This will help you get the binaries for osmdroid included in your project.

    Manifest

    In most cases, you will have to set the following authorizations in your AndroidManifest.xml:

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

    If you are only using parts of the library, you can adjust the permissions accordingly.

    Online tile provider

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"  />

    Location provider

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

    Android 6.0+ devices require you have to check for "dangerous" permissions at runtime.
    osmdroid requires the following dangerous permissions:
    WRITE_EXTERNAL_STORAGE and ACCESS_COARSE_LOCATION/ACCESS_FINE_LOCATION.
    See MainActivity.java below for reference.

    Layout

    Create a "src/main/res/layouts/main.xml" layout like this one. With Android Studio, it probably created one already. The default is called "src/main/res/layouts/activity_main.xml":

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:orientation="vertical" 
            android:layout_width="fill_parent"
            android:layout_height="fill_parent">
            <org.osmdroid.views.MapView android:id="@+id/map"
                    android:layout_width="fill_parent" 
                    android:layout_height="fill_parent" />
    </LinearLayout>

    Main Activity

    We now create the main activity (MainActivity.java):

    import android.Manifest
    import android.content.Context
    import android.content.pm.PackageManager
    import android.os.Bundle
    import android.preference.PreferenceManager
    
    import androidx.appcompat.app.AppCompatActivity
    import androidx.core.app.ActivityCompat
    import androidx.core.content.ContextCompat
    
    import org.osmdroid.config.Configuration.*
    import org.osmdroid.tileprovider.tilesource.TileSourceFactory
    import org.osmdroid.views.MapView
    
    import java.util.ArrayList
    
    class MainActivity : AppCompatActivity() {
        privat val REQUEST_PERMISSIONS_REQUEST_CODE = 1;
        private lateinit var map : MapView;  
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            //handle permissions first, before map is created. not depicted here
    
            //load/initialize the osmdroid configuration, this can be done 
            // This won't work unless you have imported this: org.osmdroid.config.Configuration.*
            getInstance().load(this, PreferenceManager.getDefaultSharedPreferences(this));
            //setting this before the layout is inflated is a good idea
            //it 'should' ensure that the map has a writable location for the map cache, even without permissions
            //if no tiles are displayed, you can try overriding the cache path using Configuration.getInstance().setCachePath
            //see also StorageUtils
            //note, the load method also sets the HTTP User Agent to your application's package name, if you abuse osm's
            //tile servers will get you banned based on this string.
    
            //inflate and create the map
            setContentView(R.layout.activity_main);
    
            map = findViewById<MapView>(R.id.map)
            map.setTileSource(TileSourceFactory.MAPNIK);
    
    
        override fun onResume() {
            super.onResume();
            //this will refresh the osmdroid configuration on resuming.
            //if you make changes to the configuration, use 
            //SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
            //Configuration.getInstance().load(this, PreferenceManager.getDefaultSharedPreferences(this));
            map.onResume(); //needed for compass, my location overlays, v6.0.0 and up
        }
    
        override fun onPause() {
            super.onPause();
            //this will refresh the osmdroid configuration on resuming.
            //if you make changes to the configuration, use 
            //SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
            //Configuration.getInstance().save(this, prefs);
            map.onPause();  //needed for compass, my location overlays, v6.0.0 and up
        }
    
        override fun onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
            ArrayList<String> permissionsToRequest = new ArrayList<>();
            for (int i = 0; i < grantResults.length; i++) {
                permissionsToRequest.add(permissions[i]);
            }
            if (permissionsToRequest.size() > 0) {
                ActivityCompat.requestPermissions(
                    this,
                    permissionsToRequest.toArray(new String[0]),
                    REQUEST_PERMISSIONS_REQUEST_CODE);
            }
        }
    
        private fun requestPermissionsIfNecessary(String[] permissions) {
            ArrayList<String> permissionsToRequest = new ArrayList<>();
            for (String permission : permissions) {
                 if (ContextCompat.checkSelfPermission(this, permission)
                        != PackageManager.PERMISSION_GRANTED) {
                    // Permission is not granted
                    permissionsToRequest.add(permission);
                }
            }
            if (permissionsToRequest.size() > 0) {
                ActivityCompat.requestPermissions(
                    this,
                    permissionsToRequest.toArray(new String[0]),
                    REQUEST_PERMISSIONS_REQUEST_CODE);
            }
        }
    }

    And that's enough to give it a try, and see the world map.

    We can move the map on a default view point. For this, we need access to the map controller:

    val mapController = map.controller
    mapController.setZoom(9.5)
    val startPoint = GeoPoint(48.8583, 2.2944);
    mapController.setCenter(startPoint);

    Advanced tutorial

    The best example of how to use the osmdroid library is our OpenStreetMapViewer sample project. It contains a basic osmdroid application plus a few special-use examples. It is recommended you use this project as an example for building your application.

    Adding a MapView

    You can add a MapView to your xml layout using:

    <org.osmdroid.views.MapView
        android:id="@+id/mapview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tilesource="Mapnik" />

    This will allow you to configure the tile source imagery for your MapView but not much else.

    However, for more control over your MapView, you will want to create a MapView programmatically.

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        map = MapView(inflater.getContext(), 256, getContext());
        return map
    }

    Map Overlays

    How to add the My Location overlay

    Note: you need manifest Fine Location permissions and if you are targeting API23+ APIs, you have to ask the user to explicitly grant location runtime permissions.

    Notice: this is a very simple example that does not handle android lifecycle correctly. Versions 5.6.5 and older, you'll need to handle automatically disabling/enabling the location provider with android life cycle events. Version 6.0.0, this is handled so long as you call map view onPause and onResume appropriately.

    locationOverlay = MyLocationNewOverlay(GpsMyLocationProvider(context), map);
    this.mLocationOverlay.enableMyLocation();
    map.overlays.add(locationOverlay)

    How to add a compass overlay

    Notice: this is a very simple example that does not handle android lifecycle correctly. Versions 5.6.5 and older, you'll need to handle automatically disabling/enabling the compass/orientation provider with android life cycle events. Version 6.0.0, this is handled so long as you call map view onPause and onResume appropriately.

    compassOverlay = new CompassOverlay(context, InternalCompassOrientationProvider(context), map);
    compassOverlay.enableCompass();
    map.overlays.add(compassOverlay);

    How to enable the Grid line Overlay

    Useful for displaying latitude/longitude grid lines.

    v5.2 up to v5.6.5, see the sample app's source code from those tagged versions.

    v6.0.0 and up

    val overlay = new LatLonGridlineOverlay2();
    map.overlays.add(overlay);

    How to enable rotation gestures

    val rotationGestureOverlay = new RotationGestureOverlay(context, mMapView);
    rotationGestureOverlay.isEnabled
    map.setMultiTouchControls(true);
    map.overlys.add(rotationGestureOverlay);

    How to add Map Scale bar overlay

    // Note, "context" refers to your activity/application context.
    // You can simply do resources.displayMetrics when inside an activity.
    // When you aren't in an activity class, you will need to have passed the context
    // to the non-activity class.
    val dm : DisplayMetrics = context.resources.displayMetrics
    val scaleBarOverlay = ScaleBarOverlay(mapView)
    scaleBarOverlay.setCentred(true)
    //play around with these values to get the location on screen in the right place for your application
    mScaleBarOverlay.setScaleBarOffset(dm.widthPixels / 2, 10);
    mMapView.overlays.add(scaleBarOverlay);

    How to add the built-in Minimap

    val minimapOverlay = MinimapOverlay(context, mMapView.tileRequestCompleteHandler);
    minimapOverlay.setWidth(dm.widthPixels / 5);
    minimapOverlay.setHeight(dm.heightPixels / 5);
    //optionally, you can set the minimap to a different tile source
    //minimapOverlay.setTileSource(....);
    map.overlays.add(minimapOverlay);

    How do I place icons on the map with a click listener?

    //your items
    val items = ArrayList<OverlayItem>()
    items.add(OverlayItem("Title", "Description", GeoPoint(0.0, 0.0)))
    
    //the overlay
    var overlay = ItemizedOverlayWithFocus<OverlayItem>(items, object:ItemizedIconOverlay.OnItemGestureListener<OverlayItem>() {
        override fun onItemSingleTapUp(index:Int, item:OverlayItem):Boolean {
            //do something
            return true
        }
        override fun onItemLongPress(index:Int, item:OverlayItem):Boolean {
            return false
        }
    }, context)
    overlay.setFocusItemsOnTap(true);
    
    mapView.overlays.add(overlay);

    How many icons can I put on the map?

    The answer is greatly dependent on what hardware the osmdroid based app is running on. A Samsung S5 (no endorsement intended) ran just fine at 3k icons and was noticeably choppy at 6k icons. Your mileage may vary. X86 Android running on modern hardware will perform great at even higher numbers. However, it's recommended to limit the amount of stuff you're rendering, if at all possible.

    If you're also drawing paths, lines, polygons, etc, then this also changes the equation. Drawing multipoint graphics is computationally more expensive and thus negatively affects performance under higher loads. To mitigate performance issues with multipoint graphics, one strategy would be to reduce the number of points handed off to the map engine when at a higher zoom level (numerically lower), then increase the fidelity as the user zoom's in. In effect, you would be clipping the visible data at the map view bounds so that the map view only "knows" about what's on screen and doesn't have to loop through all 10k icons that you want on the map. Although you can give the map view all 10k objects, but every time the map moves or zooms, it will iterate over all 10k items to calculate where to draw them (if at all). Using this mechanism paired with map motion listeners and a database query that supports geographic bounds, you can support a rich experience for users with lots of data and still have reasonable performance.

    Reusing drawables for icons will help with memory usage too.

    Map Sources, Imagery and Tile sets.

    See https://github.com/osmdroid/osmdroid/wiki/Map-Sources

    ESRI Shape File support

    Add in version 6.1.3, a support library is available that can read ESRI shape files, specifically shape and metadata files.

    • not all shape file formats are supported, such as 3d shapes.
    • the code in this library, and the dependency are asf/mit compatible. no gpl issues

    To use this, add this to your gradle build file:

    implementation 'org.osmdroid:osmdroid-shape:VERSION'
    

    In Kotlin

    folder: List<Overlay> = ShapeConverter.convert(mapView, File(myshape))
    mapView.overlayManager.addAll(folder)
    mapView.invalidate()

    Where myshape is a .shp file somewhere on the drive. If other metadata is present, it is appended to the description information for the converted item. Output is one of:

    • Marker
    • Polyline
    • Polygon

     

    MPG

    展开全文
  • OSMdroid开发

    2021-05-19 13:42:21
    OSMdroid开发 获取OSM数据 可以通过该网站下载世界各地的OpenStreetMap地图矢量数据,可以下载pbf,shapefile,geojson格式的数据。缺点:只能选择国家范围的数据,无法精确到一个省或市。 比如:从这个页面下载...

    OSMdroid开发

    获取OSM数据

    1. 可以通过该网站下载世界各地的OpenStreetMap地图矢量数据,可以下载pbf,shapefile,geojson格式的数据。缺点:只能选择国家范围的数据,无法精确到一个省或市。

      比如:从这个页面下载中国的地图,选择bz2格式,使用7-zip解压,可以得到一个osm文件,也就是xml文件。

      image-20210505231509077
    2. openstreetmap.org 网站本身提供地图数据的下载服务(范围不能过大),点击地图上端的“输出”,然后选择范围和输出格式即可,下载格式为osm格式。如果范围太大可以选择从下方的镜像站下载。

      image-20210505234410251
    3. 全球范围的数据https://planet.openstreetmap.org/

    Osmdroid的使用

    在线OSM街道地图的加载

    1. 添加依赖

      在module级别的build.gradle中的dependencies中添加

      implementation 'org.osmdroid:osmdroid-android:6.1.0'
      
      image-20210510183346674
    2. 权限配置

      打开AndroidManifest.xml文件,在application的外面添加如下的代码

      <!--添加访问权限-->
          <uses-permission android:name="android.permission.INTERNET" />
          <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
          <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
          <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
          <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
          <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
      
      image-20210510183653031
    3. MainActivity

      在其中添加如下的代码:

      public class MainActivity extends AppCompatActivity {
      
          @Override
          protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.activity_main);
      
              //获取布局文件中的mapView
              MapView mMapView = (MapView) findViewById(R.id.mapView);
              //获取地图控制器
              IMapController mcontroller = mMapView.getController();
              //设置在线地图源为MAPNIK(OSM街道)
              mMapView.setTileSource(TileSourceFactory.MAPNIK);
              //设置多指触控可用
              mMapView.setMultiTouchControls(true);
              //设置缩放按钮可见
              mMapView.getZoomController().setVisibility(CustomZoomButtonsController.Visibility.ALWAYS);
              //设置缩放界别
              mcontroller.setZoom(15);
              //添加比例尺
              ScaleBarOverlay mScaleBarOverlay = new ScaleBarOverlay(mMapView);
              mMapView.getOverlays().add(mScaleBarOverlay);
              //地图可旋转
              RotationGestureOverlay mRotationGestureOverlay = new RotationGestureOverlay(this, mMapView);
              mRotationGestureOverlay.setEnabled(true);
              mMapView.getOverlays().add(mRotationGestureOverlay);
              //设置地图中心
              GeoPoint geopoint = new GeoPoint(30.4653, 114.4281);
              MapController mMapController= (MapController) mMapView.getController();//获取MapView控制器
              mMapController.setCenter(geopoint);//设置地图中心
          }
      }
      

    启动后Osmdroid可能会出现

    android.database.sqlite.SQLiteCantOpenDatabaseException: Cannot open database ‘/storage/emulated/0/osmdroid/tiles/cache.db’: Directory /storage/emulated/0/osmdroid/tiles doesn’t exist报错,无法打开数据库

    需要在onCreate中添加如下代码

    //获取访问数据库的权限
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
    
            Context ctx = getApplicationContext();
            Configuration.getInstance().load(ctx, PreferenceManager.getDefaultSharedPreferences(ctx));
    
    展开全文
  • 使用osmdroid引擎,添加google地图图源,解决地图空白问题 实现了定位,自定义marker,画线的地图基本功能,能满足地图基本的开发

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 708
精华内容 283
关键字:

osmdroid