DEV Community

HarmonyOS
HarmonyOS

Posted on

How can the midpoint coordinate between two different locations on a map be calculated in HarmonyOS Wearable applications?

Read the original article:How can the midpoint coordinate between two different locations on a map be calculated in HarmonyOS Wearable applications?

Context

Calculating the midpoint between two geographic locations is essential in HarmonyOS Wearable applications for route planning, navigation, or visualizing meeting points between users. This allows developers to create more interactive and context-aware map features.

Description

In HarmonyOS Wearable applications, accurately determining the midpoint between two locations is crucial for enhancing map-based functionalities. Using Location Kit, developers can retrieve precise geographic coordinates of users or points of interest. These coordinates can then be processed to calculate a central point, which is particularly useful for route planning, navigation, or identifying meeting spots. Once the midpoint is calculated, Map Kit can be utilized to visualize this point on the wearable’s map interface, such as by placing a marker or highlighting the location. Leveraging both Location Kit and Map Kit ensures that developers can create interactive, real-time, and context-aware experiences on devices with limited screen space and computational resources, providing users with intuitive and practical navigation solutions.

Solution / Approach

In HarmonyOS Wearable applications, calculating and visualizing the midpoint between two locations can enhance map-based functionalities such as route planning and meeting point identification. The following approach demonstrates how to implement this feature using Location Kit and Map Kit.

1.Setup Map and Location Services:
Using MapComponent from Map Kit, the map is initialized with default options and displayed on the wearable device. Location Kit's geoLocationManager is used to retrieve the user’s current location in real-time. The locationChangeCallback updates the current location and centers the map dynamically.

   this.locationChangeCallback = (location: geoLocationManager.Location) => {
       this.currentLocation = location;
       this.centerMapOnLocation(location);
   };
   geoLocationManager.on('locationChange', this.locationRequest, this.locationChangeCallback!);
Enter fullscreen mode Exit fullscreen mode

2.Load and Display Markers for Friends:
A list of Friend objects, each with latitude and longitude properties, is loaded from a database. Markers for each friend are added to the map with relevant annotations.

   private addFriendMarkers() {
       this.friends.forEach((friend) => {
           if (friend.latitude && friend.longitude) {
               const markerOptions: mapCommon.MarkerOptions = {
                   position: { latitude: friend.latitude, longitude: friend.longitude },
                   title: friend.name,
                   clickable: true
               };
               this.mapController!.addMarker(markerOptions);
           }
       });
   }
Enter fullscreen mode Exit fullscreen mode

3.Calculate Midpoint Between Two Locations:
When a marker is clicked, the midpoint between the user’s current location and the friend’s location is calculated using spherical coordinate conversion. This ensures accuracy over the Earth's curvature.

   private calculateMidpoint(lat1: number, lon1: number, lat2: number, lon2: number): Location {
       const lat1Rad = this.toRad(lat1);
       const lon1Rad = this.toRad(lon1);
       const lat2Rad = this.toRad(lat2);
       const lon2Rad = this.toRad(lon2);

       const x1 = Math.cos(lat1Rad) * Math.cos(lon1Rad);
       const y1 = Math.cos(lat1Rad) * Math.sin(lon1Rad);
       const z1 = Math.sin(lat1Rad);

       const x2 = Math.cos(lat2Rad) * Math.cos(lon2Rad);
       const y2 = Math.cos(lat2Rad) * Math.sin(lon2Rad);
       const z2 = Math.sin(lat2Rad);

       const x = (x1 + x2) / 2;
       const y = (y1 + y2) / 2;
       const z = (z1 + z2) / 2;

       const lon = Math.atan2(y, x);
       const lat = Math.atan2(z, Math.sqrt(x * x + y * y));

       return { latitude: this.toDeg(lat), longitude: this.toDeg(lon) };
   }
Enter fullscreen mode Exit fullscreen mode

4.Visualize Midpoint and Nearby Routes:
After calculating the midpoint, a nearby search is performed using Map Kit’s site.nearbySearch, and a driving route from the current location to the nearest point of interest is retrieved via navi.getDrivingRoutes. The midpoint, route, and destination marker are then displayed on the map.

   const midPoint : Location = this.calculateMidpoint(
       this.currentLocation.latitude,
       this.currentLocation.longitude,
       clickedFriend.latitude,
       clickedFriend.longitude
   );

   const nearbySearchParams: site.NearbySearchParams = { location: midPoint, radius: 10000, pageSize: 20, pageIndex: 1 };
   const result = await site.nearbySearch(nearbySearchParams);
   const route = (await navi.getDrivingRoutes({ origins: [this.currentLocation], destination: result.sites![0].location! })).routes[0];

   const polyline: mapCommon.MapPolylineOptions = { points: route.overviewPolyline, width: 10, color: 0xFF0A84FF };
   await this.mapController!.addPolyline(polyline);
Enter fullscreen mode Exit fullscreen mode

5.Event Handling and Cleanup:
Marker click events are set up to trigger the midpoint calculation and route display. When the page disappears, location updates are unsubscribed to prevent unnecessary background operations.

   aboutToDisappear(): void {
       if (this.locationChangeCallback) {
           geoLocationManager.off('locationChange', this.locationChangeCallback);
       }
   }
Enter fullscreen mode Exit fullscreen mode

This solution combines real-time location tracking, spherical midpoint calculation, and Map Kit visualization to enable dynamic, interactive mapping features for HarmonyOS Wearable devices. Here you can find the relate screenshot below;

image.png

Key Takeaways

  1. Midpoint Calculation: Accurate midpoint computation between two geographic locations can enhance map-based functionalities such as route planning, navigation, and meeting point visualization.
  2. Integration with Location Kit: Location Kit allows real-time retrieval of the user’s current coordinates, which are essential for dynamic midpoint calculation and interactive map features.
  3. Map Kit Visualization: Map Kit can be used to display markers, polylines, and routes, enabling users to visualize midpoints, nearby points of interest, and optimized routes.
  4. Spherical Coordinate Accuracy: Using spherical coordinate conversions ensures that midpoint calculations are accurate over the Earth’s curved surface, which is important for wearable applications covering larger distances.
  5. Event-Driven Interactions: Marker click events and real-time location updates allow dynamic interactions, ensuring that map features are responsive and context-aware.

Additional Resources

https://developer.huawei.com/consumer/en/doc/harmonyos-guides/map-presenting

https://developer.huawei.com/consumer/en/doc/harmonyos-guides/map-location

https://developer.huawei.com/consumer/en/doc/harmonyos-guides/map-marker

Written by Mehmet Algul

Top comments (0)