Search code examples
androidgoogle-mapsandroid-fragmentsmymaps

Add MyMaps map to an Android Fragment


I'm currently working on a project where I need to add a Google My Maps map to a fragment, but I've been searching for a while, and I haven't been able to find a way to introduce the URL. My guess is that it should be a method somewhere in the GoogleMap class. Also, I have noticed that there are some methods like addPolygon which could help achieve a similar result as the MyMaps map. However, that would be a pretty messy approach, as I'd have to add many coordinates, and it would become really time consuming.

Thanks!


Solution

  • Im not sure about process of not saving the KML file and showing in Fragment.

    But by manually downloading the file as shown below , we can include the same in Fragment.


    enter image description here

    Now create folder raw inside res folder.

    Paste the downloaded KML file in raw folder.

    Update the dependency of google maps as shown.

    api 'com.google.maps.android:android-maps-utils:0.5'
    

    Inside your fragment do the following.

    KmlLayer kmlFile;
    
    public void onMapReady(GoogleMap googleMap) {
       ...............
       ...............
       try {
                kmlFile = new KmlLayer(googleMap, R.raw.my_map, getContext());
                kmlFile.addLayerToMap();
            } catch (XmlPullParserException e) {
                Log.e(TAG,""+e.toString());
            } catch (IOException e) {
                Log.e(TAG,""+e.toString());
            }
    }
    

    I have used below to display normal google map. This map loading is as usual procedure for showing map in Fragment

    <com.google.android.gms.maps.MapView
                    android:id="@+id/placeOrderMap"
                    android:layout_width="match_parent"
                    android:layout_height="200dp"
    >
    </com.google.android.gms.maps.MapView>
    

    Now once the Fragment is loaded, swipe to the location were you created your Google My Maps and you can see the created map Pin / Icon etc.

    The output will be as shown below according to your created elements.

    enter image description here