Miouyouyou / Android-GoogleMap-Kotlin-Example

A simple GoogleMap Android SDK example, written Kotlin
MIT License
5 stars 4 forks source link

How to pass LatLng from Main Activity to the MyMapFragment? #1

Open danwong opened 5 years ago

danwong commented 5 years ago

How would you go about sending a custom LatLng from your mainactivity to your MyMapFragment so you could customize the initialization of the map? Thanks!

Miouyouyou commented 5 years ago

Well, IMHO, the custom XML attributes might be the more "elegant" way I guess.

The simpler way would be to put public fields on the Fragment, and set them up during the container Activity "onCreate" method call, before calling any other method on it.

Another way would be :

https://developer.android.com/guide/components/fragments#EventCallbacks

Now in the Android documentation, they throw an exception if the Interface is not implemented, but you can just fallback to "default" values instead.

There might be tons of other ways, I haven't done Android development for a long period so I'm not wary of new mechanisms that could make this easier.

danwong commented 5 years ago

Awesome! What I did was add the mapFragment.getMapAsync function declaration inside what would be your MainActivity.kt

That allowed the activity to have control over the paramters rather than trying to pass in a bundle through to the fragmnent.


            mapFragment.getMapAsync {
                val ll = LatLng(latitude, longitude)
                it.addMarker(MarkerOptions()
                    .position(ll)
                    .title(title)
                    .snippet(url))
                var color = Color.RED
                if (magnitude.absoluteValue < 4) {
                    color = Color.BLUE
                } else if (magnitude.absoluteValue < 2.5) {
                    color = Color.YELLOW
                }
                it.addCircle(
                    CircleOptions()
                        .center(ll)
                        .strokeColor(color)
                        .fillColor(color)
                        .radius(magnitude.absoluteValue * 100000)
                        .visible(true)
                )
                it.moveCamera(CameraUpdateFactory.newLatLng(ll))
                it.setOnInfoWindowClickListener(this)

            }```
Miouyouyou commented 5 years ago

Interesting !

I didn't know that you could define another class method like this with Kotlin.