如何制作基于Google Maps的外部地图,仅展示指定POI?
Absolutely! You can absolutely build a custom Google Maps-based map that checks both of your boxes—here's a step-by-step breakdown to make it happen:
First up, you'll rely on two key parts of Google's Maps Platform:
- Google Maps JavaScript API: To render the interactive map and customize its appearance.
- Places API: To search for specific locations (hospitals, pharmacies) and add autocomplete/search functionality.
You'll need a valid API key (enable both APIs in your Google Cloud Console first, and set up usage restrictions to keep it secure).
There are two ways to handle this—hiding irrelevant POIs (points of interest) and actively fetching/displaying only your target locations.
Hide Irrelevant POIs with Map Styling
You can use custom map styles to turn off all default POI labels except hospitals and pharmacies. Here's a code snippet to add when initializing your map:
// Define custom map styles const mapStyles = [ // Hide all POI labels by default { featureType: "poi", elementType: "labels", stylers: [{ visibility: "off" }] }, // Show labels for hospitals { featureType: "poi.medical", elementType: "labels", stylers: [{ visibility: "on" }] }, // Show labels for pharmacies { featureType: "poi.pharmacy", elementType: "labels", stylers: [{ visibility: "on" }] } ]; // Initialize the map with your custom styles const map = new google.maps.Map(document.getElementById("map-container"), { center: { lat: 40.7128, lng: -74.0060 }, // Default center (adjust as needed) zoom: 12, styles: mapStyles });
Fetch and Display Only Targeted Locations
If you want to actively load and mark hospitals/pharmacies (instead of just showing their default labels), use the Places API's Nearby Search request:
// Initialize Places service const placesService = new google.maps.places.PlacesService(map); // Function to load hospitals/pharmacies near a given location function loadMedicalLocations(location) { placesService.nearbySearch({ location: location, // Coordinates (e.g., user's position or postcode converted to coords) radius: 5000, // Search within 5km (adjust radius as needed) type: ["hospital", "pharmacy"] // Only fetch these types }, (results, status) => { if (status === google.maps.places.PlacesServiceStatus.OK) { // Add a marker for each result results.forEach(result => { new google.maps.Marker({ map: map, position: result.geometry.location, title: result.name }); }); } }); }
To let users search by their current location or postcode, combine the Geocoding API (to convert postcodes to coordinates) with the Places API search.
Option 1: Postcode-to-Coordinates Search
Use the Geocoding API to turn a user's entered postcode into a latitude/longitude pair, then run your medical location search:
// Function to convert postcode to coordinates function geocodePostcode(postcode) { const geocoder = new google.maps.Geocoder(); geocoder.geocode({ address: postcode }, (results, status) => { if (status === google.maps.GeocoderStatus.OK && results[0]) { const location = results[0].geometry.location; map.setCenter(location); map.setZoom(14); // Load nearby hospitals/pharmacies loadMedicalLocations(location); } }); } // Attach to your search button document.getElementById("search-btn").addEventListener("click", () => { const postcode = document.getElementById("postcode-input").value; geocodePostcode(postcode); });
Option 2: Current Location Search
Use the browser's Geolocation API to get the user's current position, then load nearby medical locations:
// Get user's current location document.getElementById("use-location-btn").addEventListener("click", () => { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(position => { const userLocation = { lat: position.coords.latitude, lng: position.coords.longitude }; map.setCenter(userLocation); map.setZoom(14); loadMedicalLocations(userLocation); }); } });
Bonus: Autocomplete with Filtered Results
For a smoother user experience, add Places Autocomplete that only suggests relevant locations (including postcodes):
const autocompleteInput = document.getElementById("autocomplete-input"); const autocomplete = new google.maps.places.Autocomplete(autocompleteInput, { types: ["geocode", "establishment"], componentRestrictions: { country: "us" }, // Adjust country code as needed fields: ["formatted_address", "geometry"] }); // When user selects a place, load medical locations nearby autocomplete.addListener("place_changed", () => { const place = autocomplete.getPlace(); if (place.geometry?.location) { map.setCenter(place.geometry.location); map.setZoom(14); loadMedicalLocations(place.geometry.location); } });
- Make sure to enable all required APIs (Maps JavaScript, Places, Geocoding) in your Google Cloud Console.
- Keep an eye on your API usage to stay within free tier limits (or set up billing if you need higher volume).
- You can tweak the
typearray in Places requests to add other medical-related locations (e.g.,clinicif needed).
内容的提问来源于stack exchange,提问作者kassiusklayton

