Coder Social home page Coder Social logo

mapme's Introduction

MapMe

MapMe

Download Build Status

MapMe is an Android library for working with Maps. MapMe brings the adapter pattern to Maps, simplifying the management of markers and annotations.

MapMe supports both Google Maps and Mapbox

Download

//base dependency
compile 'nz.co.trademe.mapme:mapme:1.2.1'
  
//for Google Maps support
compile 'nz.co.trademe.mapme:googlemaps:1.2.1'
  
//for Mapbox support
compile 'nz.co.trademe.mapme:mapbox:1.2.1'

Usage

A simple MapsAdapter might look like this:

class MapsAdapter(context: Context, private val markers: List<MarkerData>) : GoogleMapMeAdapter(context) {

    fun onCreateAnnotation(factory: AnnotationFactory, position: Int, annotationType: Int): MapAnnotation {
        val item = this.markers[position]
        return factory.createMarker(item.getLatLng(), null, item.getTitle())
    }

    fun onBindAnnotation(annotation: MapAnnotation, position: Int, payload: Any) {
        if (annotation is MarkerAnnotation) {
            val item = this.markers[position]
            annotation.setTitle(item.getTitle())
        }
    }

    val itemCount: Int
        get() = markers.size()
}

Using the adapter in your view:

val adapter: MapMeAdapter = GoogleMapMeAdapter(context, items)
adapter.setOnAnnotationClickListener(this)

mapView.getMapAsync { googleMap ->
    //Attach the adapter to the map view once it's initialized
    adapter.attach(mapView, googleMap)
}

Dispatch data updates to the adapter:

// add new data and tell the adapter about it

items.addAll(myData)
adapter.notifyDataSetChanged()

// or with DiffUtil

val diff = DiffUtil.calculateDiff(myDiffCallback)
diff.dispatchUpdatesTo(adapter)

Click listeners

MapMe takes the pain out of click listeners too. No more setting tags on markers and trying to match a tag to your data when the click event is received.

MapMe has a setOnAnnotationClickListener method that will pass back a MapAnnotation containing the position of the item in the list of data:

mapsAdapter.setOnAnnotationClickListener(OnMapAnnotationClickListener { annotation ->
            //retrieve the data item based on the position
            val item = myData[annotation.position]
            
            //handle item click here
            
            true
        })

Info window clicks are handled in the same way.

Animations

While MapMe doesn't handle marker animations directly, it does provide a onAnnotationAdded method on the adapter that is called when a marker is added to the map.

This is the ideal place to start an animation.

For example, the following animates a markers alpha when it is added to the map:

override fun onAnnotationAdded(annotation: MapAnnotation) {
        if (annotation !is MarkerAnnotation) return

        ObjectAnimator.ofFloat(annotation, "alpha", 0f, 1f)
                .apply {
                    duration = 150
                    interpolator = DecelerateInterpolator()
                    start()
               }
}

Markers and Annotations

MapMe is based around the concept of Annotations. An annotation is anything displayed on the map.

The only annotation currently supported is Markers. We hope to support many more in the future.

We'd love PR's adding support for more annotations!

Multiple annotation types

More complex adapters can override getItemAnnotationType to work with multiple annotations. The annotation type is passed to onCreateAnnotation just like in a RecyclerView Adapter.

AnnotationFactory

MapMe differs from list adapters in that the creation of annotations must be left up to the map as they are not standard Android views.

The MapAdapter onCreateAnnotation method provides an AnnotationFactory as a parameter that must be used to create and return Map Annotations.

DiffUtil

As well as support for standard Adapter methods such as notifyDataSetChanged, and notifyItemInserted, MapMe supports (and recommends) DiffUtil.

DiffUtil is where the true power of MapMe comes into play. Simple manipulate the data set, calculate the diff and dispatch it to MapMe. The map will instantly reflect the data.

A DiffResult can be dispatched to the MapAdapter just as you would a RecyclerView:

DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(new MarkerDiffCallback(this.markers, newMarkers));
diffResult.dispatchUpdatesTo(mapAdapter);

Why the adapter pattern?

Working with a few map markers is simple, but working with hundreds can become a mess of spaghetti code.

The adapter pattern provides a clear separation of data from the view, allowing the data to be manipulated freely without the concern of updating the view.

We think this is a pattern fits perfectly with maps.

Contributing

We love contributions, but make sure to checkout CONTRIBUTING.MD first!

mapme's People

Contributors

avegrv avatar josh-burton avatar rwjc avatar sabintrademe avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

mapme's Issues

License Type?

Is this open source? There seems to be no licence declaration, which makes me hesitant to use you library.
Edit:
Never mind. I just can't read.

Update Mapbox

MapMe compiles an older version of Mapbox. We should use the latest!

Problems with KML and Annotation click

Hi,
I'm using Google Maps utils library to add a KML Layer to map.

All works fine (both annotations and kml layers) but when I click on marker to open a bottomsheetdialog, the listener never called and the marker shows the info windows.
If I disable the adding of KML, all works correctly.

How can I fix?

Custom animations (scale, rotate, translate) do not work?

I would like to add a custom animation when markers are attached to the adapter. Following the provided sample code from the README, the alpha animation works perfectly on my created markers (https://github.com/TradeMe/MapMe#animations):

override fun onAnnotationAdded(annotation: MapAnnotation) {
        if (annotation !is MarkerAnnotation) return

        ObjectAnimator.ofFloat(annotation, "alpha", 0f, 1f)
                .apply {
                    duration = 150
                    interpolator = DecelerateInterpolator()
                    start()
               }
}

However, when I try to implement a different animation, it doesn't seem to work, i.e. the markers simply pop up without any animation?
I've tried translation, rotationand scale as follows:

ObjectAnimator.ofFloat(annotation, "translationX", 100f).apply {
    duration = 1000
    start()
}
ObjectAnimator.ofFloat(annotation, "rotation", 360f).apply {
    duration = 1000
    start()
}
ObjectAnimator.ofFloat(annotation, "scaleX", 2f).apply {
    duration = 1000
    start()
}

Am I doing something wrong or is alpha the only supported animation on markers?
Btw.: I am using the default google maps marker icon, i.e.:

factory.createMarker(LatLng(item.lat, item.lon), null, item.title)

IndexOutOfBoundsException with an empty list

When a MapAdapter is initialized with an empty list of items, it crashes.

java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
    at java.util.ArrayList.get(ArrayList.java:437)
    at ca.llamabagel.transpo.features.map.MapAdapter.onCreateAnnotation(MapAdapter.kt:41)
    at nz.co.trademe.mapme.MapMeAdapter.createAnnotation(MapMeAdapter.kt:91)
    at nz.co.trademe.mapme.MapMeAdapter.applyUpdates(MapMeAdapter.kt:126)
    at nz.co.trademe.mapme.MapMeAdapter.consumePendingUpdateOperations$mapme_debug(MapMeAdapter.kt:514)
    at nz.co.trademe.mapme.MapMeAdapter$updateChildViewsRunnable$1.run(MapMeAdapter.kt:502)
    at android.os.Handler.handleCallback(Handler.java:789)
    at android.os.Handler.dispatchMessage(Handler.java:98)
    at android.os.Looper.loop(Looper.java:
    at android.app.ActivityThread.main(ActivityThread.java:
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)

Double notifyDataSetChanged may cause crash

I don't know if it's a bad use of the library or not, but when performing the following sequence of actions, bad things can occur.

  1. Create a list with one item and create an adapter with it
  2. Call notifyDataSetChanged(). After that, getItemCount() gets called, returning 1 as result.
  3. Immediately, and before the adapter is able to refresh its annotations, remove the single item from the list
  4. Call notifyDataSetChanged(). After that, getItemCount() gets called, returning 0 as result.
  5. In the next view refresh, the adapter calls onCreateAnnotation(...) with position=0, leading to a crash since there are no items in the list.

Apparently, the adapter remembers the first amount of annotations to be added to the map, but the second call to notifyDataSetChanged() does not get taken into account.

Low performance on adding new items

Hi i use this lib for city directory app and it cause app lag.
I measure performance and I got that these methods slow down app
I share my logcat details

I/Default-IBlockHandler: nz.co.trademe.mapme.MapAdapterHelper\dispatchSecondPass costed 3122
I/Default-IBlockHandler: nz.co.trademe.mapme.MapAdapterHelper\dispatch costed 3123
I/Default-IBlockHandler: nz.co.trademe.mapme.MapMeAdapter\applyUpdates costed 2155
I/Default-IBlockHandler: nz.co.trademe.mapme.MapMeAdapter\consumePendingUpdateOperations$mapme_release costed 5278
I/Default-IBlockHandler: nz.co.trademe.mapme.MapMeAdapter$updateChildViewsRunnable$1\run costed 5278

as you see it took near 5.3 sec to update ui

please help me

Update kotlin

Project uses org.jetbrains.kotlin:kotlin-stdlib-jre7

Parcelable encountered IOException writing serializable object (name = nz.co.trademe.mapme.googlemaps.GoogleMapMarkerAnnotation)

Hi there,

I was playing with MapMe and came across strange issue. When a new activity is started from the activity with the map, app crashes with the error:

java.lang.RuntimeException: Parcelable encountered IOException writing serializable object (name = nz.co.trademe.mapme.googlemaps.GoogleMapMarkerAnnotation)

i created this commit to demonstrate it:

dimasikturbo@b6c674c

when "remove" label is clicked the app crashes

Reduce Factory.createMarker parameters

Hi,

In general, the library is pretty simple to use but there are few parts that might be confusing.

onCreateAnnotation should use the factory to create the marker and then onBindAnnotation should actually set up the marker attributes, the way is implemented feels you have to do it onCreatAnnotation since the factory requires position, bitmap and title but also during onBindAnnotation so feels like duplicating the job.

My suggestion would be that the factory only requires a position, so the MapAnnotation constructor. Then on the create Annotation you only make sure to create the marker on the position and during onBindAnnotation you set the attrs.

interface AnnotationFactory<in Map> {
    fun createMarker(latLng: LatLng): MarkerAnnotation
    ...
}

abstract class MarkerAnnotation(latLng: LatLng) : MapAnnotation() {
...
}

// MyAdapter...
override fun onBindAnnotation(annotation: MapAnnotation, position: Int, payload: Any?) {
    // Set the attributes to the annotation
}

override fun onCreateAnnotation(factory: AnnotationFactory, position: Int, annotationType: Int): MapAnnotation {
    val item = this.markers[position]
    return factory.createMarker(LatLng(item.latitude, item.longitude)
}

Crash

After add library crash
FATAL EXCEPTION: main java.lang.NoSuchMethodError: No static method zzb(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object; in class Lcom/google/android/gms/common/internal/zzbo; or its super classes (declaration of 'com.google.android.gms.common.internal.zzbo com.google.firebase.provider.FirebaseInitProvider.attachInfo(Unknown Source)

Markers don't attach to map in special case

If I pass to the method MapMeAdapter#attach blank view, that doesn't attached to a window - at this case I don't have any markers on map.

It's seem to be problem at method MapMeAdapter#triggerUpdateProcessor.
According to the documentation, the post(...) should be called from non-UI threads only when the View is attached to a window. My view doesn't attached to a window.

Why a need to attach mapView to adapter?
I don't use MapView, I use SupportMapFragment to represent map.

androidX support

Since MapMeAdapter inherits ListUpdateCallback from the legacy support library, the adapter cannot be used with androidX's DiffUtil.DiffResult.dispatchUpdatesTo().

Mocking framework

Hi,

hope find you well with this cold call.

I am an author of mocking framework for Kotlin

I see you are using mockito-kotlin.

I just want you to be aware that there is solution that fully supports Kotlin and ask to try it in your new/current projects.

I can help you if you answer to this issue.

Thanks and please star it

googlemaps pom incorrect

Hi when updating to 1.0.5 for the google maps version the base dependency is not referenced correctly in the pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <modelVersion>4.0.0</modelVersion>
  <groupId>nz.co.trademe.mapme</groupId>
  <artifactId>googlemaps</artifactId>
  <version>1.0.5</version>
  <packaging>aar</packaging>
  <description>MapMe is an Android library that brings the adapter pattern to Maps, simplifying the management of markers and annotations.</description>
  <name>MapMe GoogleMaps</name>
  <url>https://github.com/TradeMe/MapMe.git</url>
  <licenses>
    <license>
      <name>MIT License</name>
      <url>http://www.opensource.org/licenses/mit-license.php</url>
      <distribution>repo</distribution>
    </license>
  </licenses>
  <scm>
    <url>https://github.com/TradeMe/MapMe.git</url>
  </scm>
  <dependencies>
    <dependency>
      <groupId>com.google.android.gms</groupId>
      <artifactId>play-services-maps</artifactId>
      <version>11.8.0</version>
    </dependency>
    <dependency>
      <groupId>com.android.support</groupId>
      <artifactId>appcompat-v7</artifactId>
      <version>27.0.1</version>
    </dependency>
    <dependency>
      <groupId>MapMe</groupId>
      <artifactId>mapme</artifactId>
      <version>unspecified</version>
    </dependency>
    <dependency>
      <groupId>org.jetbrains.kotlin</groupId>
      <artifactId>kotlin-stdlib-jre7</artifactId>
      <version>1.2.31</version>
    </dependency>
  </dependencies>
</project>

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.