Created
April 23, 2023 21:42
-
-
Save muath-ye/0f9006b9408b9b9d976c4f177120be62 to your computer and use it in GitHub Desktop.
A step-by-step tutorial explaining how to use the Google Maps JavaScript API to display a map and allow the user to choose a location.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<title>Choose Your Location</title> | |
</head> | |
<body> | |
<!-- A div to contain the map --> | |
<div id="map" style="height: 400px; width: 100%;"></div> | |
<!-- Script to load the Google Maps API and create the map --> | |
<script src="https://maps.googleapis.com/maps/api/js?key={{ config('app.google.maps') }}&callback=Function.prototype"></script> | |
<script> | |
// Set default map options, including center and zoom level | |
var mapOptions = { | |
center: new google.maps.LatLng(0, 0), // Default to center of the world | |
zoom: 2 // Default zoom level | |
}; | |
// Create a new map object in the "map" div with the default map options | |
var map = new google.maps.Map(document.getElementById("map"), mapOptions); | |
// If the user's browser supports geolocation, try to get the user's current location | |
if (navigator.geolocation) { | |
navigator.geolocation.getCurrentPosition(function(position) { | |
// If successful, create a marker at the user's current location | |
var userLatLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude); | |
var marker = new google.maps.Marker({ | |
position: userLatLng, | |
map: map, | |
draggable: true // Allow the user to drag the marker to choose a location | |
}); | |
// Center the map on the user's location and zoom in for detail | |
map.setCenter(userLatLng); | |
map.setZoom(13); | |
// Add an event listener to the marker's dragend event, which fires when the user finishes dragging the marker | |
google.maps.event.addListener(marker, "dragend", function() { | |
// Log the latitude and longitude of the marker's new position to the console | |
var latLng = marker.getPosition(); | |
console.log("Chosen location: " + latLng.lat() + ", " + latLng.lng()); | |
}); | |
}, function() { | |
// If geolocation fails, create a marker at the center of the map | |
console.log("Geolocation service failed."); | |
var marker = new google.maps.Marker({ | |
position: map.getCenter(), | |
map: map, | |
draggable: true | |
}); | |
// Add an event listener to the marker's dragend event, as before | |
google.maps.event.addListener(marker, "dragend", function() { | |
var latLng = marker.getPosition(); | |
console.log("Chosen location: " + latLng.lat() + ", " + latLng.lng()); | |
}); | |
}); | |
} else { | |
// If geolocation is not supported, create a marker at the center of the map | |
console.log("Geolocation service not supported."); | |
var marker = new google.maps.Marker({ | |
position: map.getCenter(), | |
map: map, | |
draggable: true | |
}); | |
// Add an event listener to the marker's dragend event, as before | |
google.maps.event.addListener(marker, "dragend", function() { | |
var latLng = marker.getPosition(); | |
console.log("Chosen location: " + latLng.lat() + ", " + latLng.lng()); | |
}); | |
} | |
</script> | |
</body> | |
</html> |
The full code of the tutorial
<!DOCTYPE html>
<html>
<head>
<title>Choose Your Location</title>
</head>
<body>
<!-- A div to contain the map -->
<div id="map" style="height: 400px; width: 100%;"></div>
<!-- Script to load the Google Maps API and create the map -->
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=Function.prototype"></script>
<script>
var mapOptions = {
center: new google.maps.LatLng(0, 0), // Default to center of the world
zoom: 2 // Default zoom level
};
// Create a new map object in the "map" div with the default map options
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
// If successful, create a marker at the user's current location
var userLatLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var marker = new google.maps.Marker({
position: userLatLng,
map: map,
draggable: true // Allow the user to drag the marker to choose a location
});
// If successful, center the map on the user's location and zoom in for detail
map.setCenter(userLatLng);
map.setZoom(13);
google.maps.event.addListener(marker, "dragend", function() {
// Log the latitude and longitude of the marker's new position to the console
var latLng = marker.getPosition();
console.log("Chosen location: " + latLng.lat() + ", " + latLng.lng());
});
}, function() {
// If geolocation fails, create a marker at the center of the map
var marker = new google.maps.Marker({
position: map.getCenter(),
map: map,
draggable: true
});
google.maps.event.addListener(marker, "dragend", function() {
// Log the latitude and longitude of the marker's new position to the console
var latLng = marker.getPosition();
console.log("Chosen location: " + latLng.lat() + ", " + latLng.lng());
});
});
} else {
// If geolocation fails, create a marker at the center of the map
var marker = new google.maps.Marker({
position: map.getCenter(),
map: map,
draggable: true
});
google.maps.event.addListener(marker, "dragend", function() {
// Log the latitude and longitude of the marker's new position to the console
var latLng = marker.getPosition();
console.log("Chosen location: " + latLng.lat() + ", " + latLng.lng());
});
}
</script>
</body>
</html>
blade example
An example for Laravel blade that stores the current location when validation failed or retrieve the address from db
This blade can be used for create and update forms at the same time
@extends('../layouts/side-menu')
@section('breadcrumb_list')
<ol class="breadcrumb">
<li class="breadcrumb-item"><a href="#">Application</a></li>
<li class="breadcrumb-item"><a href="{{ route('admin.providers.list') }}">Providers</a></li>
<li class="breadcrumb-item active" aria-current="page">{{ $mode == 'create' ? 'Create Clinic Account' : 'Edit Clinic Account' }}</li>
</ol>
@endsection
@section('subcontent')
<h2 class="mt-10 text-lg font-medium intro-y">{{ $mode == 'create' ? 'Add New Clinic Account' : 'Edit Clinic Account' }}</h2>
<div class="grid grid-cols-12 gap-6">
<div class="col-span-12 lg:col-span-12 2xl:col-span-12">
<!-- BEGIN: Display Information -->
<form method="POST" action="{{ route($mode == 'create' ? 'admin.providers.add' : 'admin.providers.edit') }}"
enctype="multipart/form-data">
<div class="intro-y box lg:mt-5">
<div class="p-5">
<div class="flex flex-col flex-col-reverse xl:flex-row">
<div class="flex-1 mt-6 xl:mt-0">
<div class="grid grid-cols-12 gap-x-5">
<div class="col-span-12">
<div class="mt-3">
<label for="address" class="form-label">Address</label>
<input type="hidden" id="address" name="address" value="{{ old('address') ?? $provider->address }}" />
<input id="search-box" type="text" class="form-control" />
<div id="map" style="height: 400px; width: 100%;"></div>
</div>
</div>
</div>
<button type="submit" class="w-20 mt-3 btn btn-primary">Save</button>
</div>
</div>
</div>
</div>
</form>
</div>
</div>
@endsection
@section('subscript')
<!-- Script to load the Google Maps API and create the map -->
<script src="https://maps.googleapis.com/maps/api/js?key={{ config('app.google.maps') }}&callback=Function.prototype&libraries=places"></script>
<script>
function initMap() {
let lat = 0;
let lng = 0;
try {
lat = JSON.parse(document.getElementById("address").value).lat;
lng = JSON.parse(document.getElementById("address").value).lng;
} catch(e) {
console.error(e);
}
var mapOptions = {
center: new google.maps.LatLng(lat, lng),
zoom: 2,
disableDefaultUI: true
};
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
var input = document.getElementById("search-box");
var searchBox = new google.maps.places.SearchBox(input);
var marker = new google.maps.Marker({
position: map.getCenter(),
map: map,
draggable: true
});
google.maps.event.addListener(marker, "dragend", function() {
var latLng = marker.getPosition();
console.log("Dragend location: " + latLng.lat() + ", " + latLng.lng());
var geocoder = new google.maps.Geocoder();
geocoder.geocode({location: latLng}, function(results, status) {
if (status === google.maps.GeocoderStatus.OK) {
if (results[0]) {
console.log("Init location name: " + results[0].formatted_address);
console.log("Init place ID: " + results[0].place_id);
// JSON object to assign to input value
var jsonData = {
formatted_address: results[0].formatted_address,
place_id: results[0].place_id,
lat: latLng.lat(),
lng: latLng.lng(),
};
// Convert JSON object to string
var jsonString = JSON.stringify(jsonData);
// Assign string to input value
document.getElementById("address").value = jsonString;
console.log(jsonString);
} else {
console.log("No results found");
}
} else {
console.log("Geocoder failed due to: " + status);
}
});
});
searchBox.addListener("places_changed", function() {
var places = searchBox.getPlaces();
if (places.length == 0) {
return;
}
var place = places[0];
var newLatLng = place.geometry.location;
marker.setPosition(newLatLng);
map.setCenter(newLatLng);
var latLng = marker.getPosition();
console.log("Chosen location: " + latLng.lat() + ", " + latLng.lng());
console.log("Chosen location name: " + place.name);
console.log("Chosen place ID: " + place.place_id);
// JSON object to assign to input value
var jsonData = {
formatted_address: place.name,
place_id: place.place_id,
lat: latLng.lat(),
lng: latLng.lng(),
};
// Convert JSON object to string
var jsonString = JSON.stringify(jsonData);
// Assign string to input value
document.getElementById("address").value = jsonString;
});
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var userLatLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
marker.setPosition(userLatLng);
map.setCenter(userLatLng);
map.setZoom(13);
var latLng = marker.getPosition();
console.log("Init location: " + latLng.lat() + ", " + latLng.lng());
var geocoder = new google.maps.Geocoder();
geocoder.geocode({location: latLng}, function(results, status) {
if (status === google.maps.GeocoderStatus.OK) {
if (results[0]) {
console.log("Init location name: " + results[0].formatted_address);
console.log("Init place ID: " + results[0].place_id);
// JSON object to assign to input value
var jsonData = {
formatted_address: results[0].formatted_address,
place_id: results[0].place_id,
lat: latLng.lat(),
lng: latLng.lng(),
};
// Convert JSON object to string
var jsonString = JSON.stringify(jsonData);
// Assign string to input value
document.getElementById("address").value = jsonString;
} else {
console.log("No results found");
}
} else {
console.log("Geocoder failed due to: " + status);
}
});
});
}
}
initMap();
</script>
@endsection
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Introduction
The Google Maps JavaScript API allows developers to embed Google Maps in web pages using JavaScript. In this tutorial, we'll walk through how to use the API to display a map and allow the user to choose a location using the provided code.
Prerequisites
Before we get started, you'll need a Google Maps API key. To get one, follow the instructions in this guide: https://developers.google.com/maps/gmp-get-started#create-project
Step 1: Set up the HTML file
Create a new HTML file and save it with a name of your choice. In this tutorial, we'll call it "choose-location.html". Add the following code to the file:
Replace YOUR_API_KEY in the script tag with your own API key.
Step 2: Create a new map object
In the script tag, create a new map object using the
google.maps.Map
constructor. The first argument is the DOM element where the map will be displayed. In this case, it's the mapdiv
that's defined in the HTML code. The second argument is an object that sets the default options for the map. In the code provided, the center of the map is set to(0, 0)
, and the default zoom level is set to2
.Step 3: Add geolocation support
The code checks if the user's browser supports geolocation. If it does, it uses the
navigator.geolocation.getCurrentPosition
method to get the user's current position. If it doesn't, it creates a marker at the center of the map.Step 4: Create a marker
Create a new marker using the
google.maps.Marker
constructor. The first argument is an object that sets the marker's options. In this case, the position of the marker is set to the user's current location (if available), or the center of the map (if geolocation is not supported). The draggable option is set to true, which allows the user to drag the marker to choose a new location.Step 5: Center the map
If the user's location is available, center the map on their location using the
map.setCenter
method. The zoom level is also set to13
to provide more detail.Step 6: Add a dragend event listener
Add an event listener to the marker's dragend event using the
google.maps.event.addListener
method. This event fires when the user finishes dragging the marker. The listener logs the latitude and longitude of the marker's new position to the console.Step 7: Test the code
Save the HTML file and open it in a web browser. If everything is set up correctly, you should see a map displayed with a marker at the user's current location (if available), or at the center of the map (if geolocation is not supported). You can drag the marker to choose a new location, and the latitude and longitude of the new location will be logged to the console.
Conclusion
In this tutorial, you learned how to use the Google Maps JavaScript API to display a map and allow the user to choose a location using the provided code. You can customize the map's options and add additional features by exploring the API documentation: https://developers.google.com/maps/documentation/javascript/overview.