Skip to main content
GuidesAPI ReferenceExamples

Fragment Map

Estimated reading time: 2 minutes

In this guide you will learn how to render an interactive map centered on a desired location. The map is fully 3D, supporting pan, pinch-zoom, rotate and tilt.

Setup

  1. Get your Magic Lane API key token: if you do not have a token, see the Getting Started guide.
  2. Download the Maps & Navigation SDK for Android archive file.
  3. Download the HelloFragment project archive file or clone the project with git.
  4. See the Configure Android Example guide.

Run the example


An android device should be connected via USB cable. Press SHIFT+F10 to compile, install and run the example on the android device.

How it works

You can open the MainActivity.kt file to see how an interactive map is rendered in a fragment.

How it works

class FirstFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_first, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
view.findViewById<Button>(R.id.button_first).setOnClickListener {
findNavController().navigate(R.id.action_FirstFragment_to_SecondFragment)
}
}
}

The first fragment.

class SecondFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_second, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
view.findViewById<Button>(R.id.button_second).setOnClickListener {
findNavController().navigate(R.id.action_SecondFragment_to_FirstFragment)
}
}
}

The second fragment.
Each of the 2 fragments has a button to navigate to the other fragment, see res/navigation/nav_graph.xml in the project.
The SecondFragment also renders a map.
First it creates a view in the fragment, onCreateView and then it overrides the onViewCreated function which defines the listener for the button to return to the first fragment.

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
if (!Util.isInternetConnected(this)) {
Toast.makeText(this, "You must be connected to internet!",
Toast.LENGTH_LONG).show()
}
}

MainActivity overrides the onCreate() function which checks that internet access is available, and loads the map setContentView(R.layout.activity_main) as defined in res/layout/activity_main.xml.

Android Examples

Maps SDK for Android Examples can be downloaded or cloned with Git.