无需使用Direction API,能否在地图上绘制两点间的路线?
Absolutely, you can pull this off—though how straightforward it is depends on whether you need a simple straight line or a real-world road-aligned route. Let’s break this down:
1. Straight-Line Route (No Road Alignment)
This is the easy one. Every major mapping API (Google Maps, Leaflet, Mapbox, etc.) has built-in tools to draw a polyline between two coordinates, no Directions API required.
For example, using the Google Maps JavaScript API, here’s a quick snippet to draw a red line between San Francisco and San Jose:
// Initialize the map const map = new google.maps.Map(document.getElementById("map"), { zoom: 9, center: { lat: 37.5665, lng: -122.0363 }, // Midpoint }); // Define start and end points const routeCoordinates = [ { lat: 37.7749, lng: -122.4194 }, // SF { lat: 37.3382, lng: -121.8863 }, // San Jose ]; // Create and add the polyline to the map const routeLine = new google.maps.Polyline({ path: routeCoordinates, geodesic: true, // Follows the curve of the Earth strokeColor: "#FF0000", strokeOpacity: 1.0, strokeWeight: 3, }); routeLine.setMap(map);
This works for any mapping library—just look for their polyline/path drawing component.
2. Real-World Road Route (No Directions API)
This is more involved, but totally doable if you need a route that follows actual roads:
- Step 1: Get road network data
You’ll need access to a dataset of roads, like OpenStreetMap (OSM) data. You can download specific regions via OSM’s API or tools like Overpass Turbo to extract road nodes and segments. - Step 2: Implement a pathfinding algorithm
Use algorithms like Dijkstra’s or A* to calculate the shortest (or fastest) path between your start and end points using the road network data. You’ll have to model the roads as a graph of nodes and edges. - Step 3: Draw the calculated path
Once you have the sequence of coordinates that make up the road route, use your mapping library’s polyline tool to render it on the map, just like the straight line example.
Important Caveats
- You won’t get the perks of a dedicated Directions API: real-time traffic updates, route optimization for time/distance/tolls, or turn-by-turn instructions.
- Handling large road networks can be computationally heavy—you might need to host and pre-process the data locally if you’re building an offline app.
Final Verdict
If you just need a quick straight line between two points? Piece of cake, no Directions API needed. If you need a road-following route? It’s feasible, but be prepared to invest time in data handling and pathfinding logic.
内容的提问来源于stack exchange,提问作者Drwin

