“This article has participated in the good article call order activity, click to see: back end, big front end double track submission, 20,000 yuan prize pool for you to challenge!”
First steps:
Complete the SDK setup according to the steps in the official document, including:
- local.propertiesTo declare yourGOOGLE_API_KEY;
- AndroidManifest.xmlAnd map the API key previously added.
- In the root – levelbuild.gradleTo add the following dependencies:
buildscript {
dependencies {
// ...
classpath "Com. Google. Android. Libraries. Mapsplatform. Secrets - gradle - plugin: secrets - gradle - plugin: 1.2.0"}}Copy the code
- In the app – levelbuild.gradleTo add the following dependencies:
plugins {
// ...
id 'com.google.android.libraries.mapsplatform.secrets-gradle-plugin'
}
dependencies {
// ...
implementation "Com. Google. Android. GMS: play - services - maps: 17.0.1"
implementation "Com. Google maps. The android: android maps - utils: 0.5"
}
Copy the code
- Sync Gradle
Google Map Fragment
First, add an element in the Layout where you want to display the GoogleMap. For example:
<fragment
android:id="@+id/google_map_fragment"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="20dp"
tools:context="com.arctos.mochabear.mapdemo.GoogleMapDemoActivity" />
Copy the code
Two points to note here:
android:name="com.google.android.gms.maps.SupportMapFragment
Set the fragment type to SupportMapFragment.If not set, an error will be reported;tools:context="com.arctos.mochabear.mapdemo.GoogleMapDemoActivity"
Set the activity corresponding to the fragment to GoogleMapDemoActivity.If not set, an error will be reported.
Then go to the Activity that displays GoogleMap, in this case GoogleMapDemoActivity, and note two things:
- This Activity implements the OnMapReadyCallback interface. In onMapReady(GoogleMap GoogleMap), you can get the corresponding GoogleMap instance.
onCreate()
Method needs to call supportFragmentManager. FindFragmentById (R.i d.g oogle_map_fragment) ` for instance of the fragments and transformation into SupportMapFragment;
The example code is as follows:
class GoogleMapDemoActivity : AppCompatActivity(), OnMapReadyCallback {
private lateinit var googleMap: GoogleMap
override fun onCreate(savedInstanceState: Bundle?). {
super.onCreate(savedInstanceState)
// Get the SupportMapFragment instance and send notification when googleMap is loaded
val mapFragment = supportFragmentManager.findFragmentById(R.id.google_map_fragment) as? SupportMapFragment mapFragment? .getMapAsync(this)}override fun onMapReady(googleMap: GoogleMap) {
// Get the loaded GoogleMap instance
this.googleMap = googleMap
}
}
Copy the code
Marker
Marker can be used to mark and explain any position on the map. Simply load the example code of Marker:
val melbourneLocation = LatLng(-37.813.144.962)
val melbourne = map.addMarker(
MarkerOptions().position(melbourneLocation)
)
Copy the code
Marker set
The marker setting is completed by calling various methods of the MarkerOptions class. Some commonly used setting methods are as follows:
val melbourneLocation = LatLng(-37.813.144.962)
val melbourne = map.addMarker(
MarkerOptions()
.position(melbourneLocation)
.anchor(0.5 f.0.5 f) // Set Marker anchor point, (0.0,0.0) represents the upper left, (1.0,1.0) represents the lower right
.rotation(90.0 f) // Set the rotation Angle
.flat(true) // Set whether Marker rotates with the map
.zIndex(1.0 f) // Set the z-axis coordinates. The larger the value, the more marker is on top of the rendering
.alpha(0.7 f) // Set transparency
.title("custom title") // Customize the title
.snippt("any random snippt") // Customize snippt
.icon(BitmapDescriptorFactory.fromBitmap(bitmap)) // Customize the bitmap icon
)
Copy the code
Marker custom layout
Using the custom marker_layout. XML layout to set the marker icon is actually an extra step: The layout file needs to be bound to data and the corresponding bitmap is generated. The instance code is as follows:
val customMarkerView = layoutInflater.inflate(R.layout.marker_layout, null)
// Bind the data of each view in the custom layout, such as title, description, etccustomMarkerView.findViewById<TextView>(R.id.custom_marker_title)? .apply { text = title } customMarkerView.findViewById<TextView>(R.id.customer_marker_description)? .apply { text = description }// Call the IconGenerator class in the Google Map SDK
val iconGenerator = IconGenerator(context) // Context instance of Acvitity is required here
iconGenerator.setContentView(customMarkerView)
iconGenerator.setBackground(null)
// Call makeIcon() to get the bitmap
val customIconBitMap = iconGenerator.makeIcon()
// Call the icon() method to use the generated bitmap as marker icon
googleMap.addMarker(
MarkerOptions()
.position(destination)
.anchor(0.0 f.1.0 f)
.icon(BitmapDescriptorFactory.fromBitmap(customIconBitMap))
)
Copy the code
InfoWindow
InfoWindow is used to introduce and explain a marker in more detail. Clicking on a marker can open/close an InfoWindow. It should be noted that only one InfoWindow will be opened at the same time, and clicking on a new InfoWindow will close the last one. To display the default InfoWindow, do the following:
val melbourneLocation = LatLng(-37.813.144.962)
val melbourne = map.addMarker(
MarkerOptions()
.position(melbourneLocation)
.title("this is info window title")
.snippet("this is info window snippt")
)
melbourne.showInfoWindow()
Copy the code
InfoWindow set
The data for InfoWindow itself is set by calling the markeroptions.title () and markeroptions.snippt () methods, but there are no other tweaked built-in methods. If you need more Settings, you can only customize the View of InfoWindow.
Customize the InfoWindow view
Custom InfoWindow lies in: to create a subclass implementation forward. Google InfoWindowAdapter () interface, example code is as follows:
googleMap.setInfoWindowAdapter(object : GoogleMap.InfoWindowAdapter {
override fun getInfoWindow(p0: Marker): View {
// The view returned here uses the entire InfoWindow space, including frame and background
val view: View = layoutInflater.inflate(R.layout.google_map_custom_infowindow, null)
val titleView = view.findViewById<View>(R.id.infowindow_title) as TextView
val descriptionView = view.findViewById<View>(R.id.infowindow_description) as TextView
titleView.text = marker.title
descriptionView.text = marker.description
return view
}
override fun getInfoContents(p0: Marker): View? {
// The view returned here will use the default frame and background of InfoWindow itself
return null}})Copy the code
Note that: This implementation forward. Google InfoWindowAdapter () subclass is applied to the entire forward of Google, which means it for each marker are on the same map, so, if the marker for different need to implement different InfoWindow, It may be necessary to pass the Marker object itself into the method getInfoWindow() or getInfoContents() to judge the Marker.
Adjust the lens Angle
The easiest way to adjust the view is to create a LatLngBounds instance and pass in the LatLng coordinates of southwest, Northeast, as follows:
val sw = LatLng(39.907935.116.392183) // View southwest coordinates (bottom left)
val ne = LatLng(39.923541.116.402244) // View northeast coordinate (top right)
val latLngBounds = LatLngBounds(sw, ne)
/ / by CameraUpdateFactory newLatLngBounds () method to construct boundary and moving scenes, 30 for padding
googleMap.moveCamera(CameraUpdateFactory.newLatLngBounds(latLngBounds, 30))
Copy the code
If you need the adaptive camera Angle and contains all the marker on the map, you can call SphericalUtil.com puteOffset () method to compute the display area of each marker (coordinates in northeast and southwest coordinates obtained by calculation), You then add it via the latlngbounds.builder ().include() method, and then call Builder().build to construct a LatLngBound instance. Example code:
val builder = LatLngBounds.Builder()
for (marker in markers) {
// show marker on map here...
// Calculate the northeast and Southwest coordinates of each marker
val markerNorthEastBorder = marker.location.let {
SphericalUtil.computeOffset(it, 500.0.0.0) // Extend 500 meters due north
SphericalUtil.computeOffset(it, 500.0.90.0) // It expands 500 meters due east
}
val markerSouthWestBorder = marker.location.let {
SphericalUtil.computeOffset(it, 500.0.180.0) // It expands 500 meters due south
SphericalUtil.computeOffset(it, 500.0.270.0) // It expands 500 meters due west
}
// Add marker to display the boundary of the region
builder.include(markerNorthEastBorder)
builder.include(markerSouthWestBorder)
}
// Construct the display boundary and move the camera
googleMap.moveCamera(CameraUpdateFactory.newLatLngBounds(builder.build(), 0))
Copy the code
Code sample
Github MochaBear – mapdemo
Refer to the link
Google Map SDK for Android