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> |
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
The full code of the tutorial