You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于Google Maps API的GPS追踪方案:如何实现到预设地点的导航?

Hey Miguel, nice to help you out with this! Since you already have your current GPS location locked in, integrating Google Maps API for navigation to a preset destination is totally doable—let’s walk through the steps with practical examples for common platforms.

Core Prerequisites First

Before diving into code, make sure you’ve got these sorted:

  • A valid Google Cloud API key (create one in the Google Cloud Console if you don’t have it)
  • Enabled the required APIs for your platform:
    • For web apps: Maps JavaScript API and Directions API
    • For mobile (Android/iOS): Maps SDK for Android/Maps SDK for iOS plus Directions API
  • Proper permissions: Mobile apps need location access permissions, and web apps need user consent (though you said you already have the current location, so this might be done already)

Web Implementation (JavaScript)

If you’re building a web-based solution, here’s how to render the route in your map and even launch full navigation:

First, load the Google Maps JS API in your HTML (replace YOUR_API_KEY with your actual key):

<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=directions"></script>
<div id="map" style="height: 400px; width: 100%;"></div>

Then add the JavaScript to handle routing and navigation:

// Your pre-fetched current location (replace with your actual coords)
const currentLocation = { lat: 40.712776, lng: -74.005974 };
// Your preset destination
const destination = { lat: 34.052235, lng: -118.243683 };

// Initialize the map centered on your current location
const map = new google.maps.Map(document.getElementById("map"), {
  center: currentLocation,
  zoom: 14,
});

// Set up directions service (to fetch routes) and renderer (to draw routes on the map)
const directionsService = new google.maps.DirectionsService();
const directionsRenderer = new google.maps.DirectionsRenderer();
directionsRenderer.setMap(map);

// Request the route from Google's API
const routeRequest = {
  origin: currentLocation,
  destination: destination,
  travelMode: google.maps.TravelMode.DRIVING, // Options: DRIVING, WALKING, TRANSIT, BICYCLING
};

directionsService.route(routeRequest, (result, status) => {
  if (status === google.maps.DirectionsStatus.OK) {
    // Draw the route on the map
    directionsRenderer.setDirections(result);
    
    // Optional: Create a link to launch full Google Maps navigation
    const navUrl = `https://www.google.com/maps/dir/?api=1&origin=${currentLocation.lat},${currentLocation.lng}&destination=${destination.lat},${destination.lng}&travelmode=driving`;
    // You can add a button that triggers window.open(navUrl) for users to start turn-by-turn navigation
  } else {
    console.error(`Oops, couldn't get directions: ${status}`);
    // Handle errors like invalid locations, quota limits, etc.
  }
});

Mobile Implementation

Android (Kotlin)

For Android, you can either launch the Google Maps app for full navigation, or render the route directly in your app’s map view. Here’s the simplest way to launch navigation:

// Your current location and destination (replace with your actual LatLng objects)
val currentLocation = LatLng(40.712776, -74.005974)
val destination = LatLng(34.052235, -118.243683)

// Build the Google Maps navigation intent
val navUri = Uri.parse("google.navigation:q=${destination.latitude},${destination.longitude}&mode=d")
val navIntent = Intent(Intent.ACTION_VIEW, navUri)
navIntent.setPackage("com.google.android.apps.maps") // Ensure it opens in Google Maps

// Check if Google Maps is installed before launching
if (navIntent.resolveActivity(packageManager) != null) {
    startActivity(navIntent)
} else {
    // Fallback: Open web-based navigation
    val webUri = Uri.parse("https://www.google.com/maps/dir/?api=1&origin=${currentLocation.latitude},${currentLocation.longitude}&destination=${destination.latitude},${destination.longitude}&travelmode=driving")
    startActivity(Intent(Intent.ACTION_VIEW, webUri))
}

iOS (Swift)

Similar to Android, you can launch the Google Maps app or fall back to the web:

// Your current location and destination (replace with your actual CLLocationCoordinate2D)
let currentLocation = CLLocationCoordinate2D(latitude: 40.712776, longitude: -74.005974)
let destination = CLLocationCoordinate2D(latitude: 34.052235, longitude: -118.243683)

// Try opening Google Maps app first
if let mapsUrl = URL(string: "comgooglemaps://?saddr=\(currentLocation.latitude),\(currentLocation.longitude)&daddr=\(destination.latitude),\(destination.longitude)&directionsmode=driving") {
    if UIApplication.shared.canOpenURL(mapsUrl) {
        UIApplication.shared.open(mapsUrl, options: [:], completionHandler: nil)
    } else {
        // Fallback to web navigation
        if let webUrl = URL(string: "https://www.google.com/maps/dir/?api=1&origin=\(currentLocation.latitude),\(currentLocation.longitude)&destination=\(destination.latitude),\(destination.longitude)&travelmode=driving") {
            UIApplication.shared.open(webUrl)
        }
    }
}
Key Things to Remember
  • API Quotas & Billing: Google Maps APIs are paid, so keep an eye on your usage in the Google Cloud Console to avoid unexpected charges.
  • Error Handling: Always check the status response from the Directions API—common issues include OVER_QUERY_LIMIT (too many requests) or NOT_FOUND (invalid location coordinates).
  • Travel Modes: Adjust the travelmode parameter based on your use case (driving, walking, etc.) to get accurate routes.

内容的提问来源于stack exchange,提问作者Miguel Esteves

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:17:33