Open Location Code on click
Example of clicking on a map and computing the Open Location Code.
by bd22
HTML
<script src="https://maps.googleapis.com/maps/api/js"></script>
<script src="https://fonts.googleapis.com/css?family=Roboto:100"></script>
<script src=" https://cdn.jsdelivr.net/openlocationcode/1.0.0/openlocationcode.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.0/jquery.min.js"></script>
<div id="code-display">
Click on the map to get the plus code
<br/> (You can zoom, drag and pan)
</div>
<!-- Container for the map -->
<div id="map-canvas"></div>
<!-- Container for displaying the Open Location Code. -->
CSS
#map-canvas {
width: 100%;
height: 200px;
}
#code-display {
font-family: Roboto, sans;
font-weight: 100;
line-height: 150%;
width: 100%;
padding: 15px;
text-align: center;
background: #fff;
border-bottom-left-radius: 5px;
border-bottom-right-radius: 5px;
}
JavaScript
// This demonstrates displaying a map and the Open Location Code of any
// clicks on the map.
// Normally, you would load the following Javascript in the HEAD section of your page:
// https://maps.googleapis.com/maps/api/js
// https://cdn.jsdelivr.net/openlocationcode/1.0.0/openlocationcode.min.js
// (or obtain your own copy from github.com/google/open-location-code)
// Here, they are defined as external resources.
var firebaseConfig = {
apiKey: "AIzaSyBHo0Bj2qQOnPJNYn5I9Rp7UgTul9n44rg",
authDomain: "development-56a6c.firebaseapp.com",
databaseURL: "https://development-56a6c.firebaseio.com",
projectId: "development-56a6c",
storageBucket: "development-56a6c.appspot.com",
messagingSenderId: "1007182456732",
appId: "1:1007182456732:web:3a9c734285f6e8b2dbca59"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
// Create a marker object.
var marker = null;
var outline = null;
// Create the map object.
var map = new google.maps.Map(
document.getElementById('map-canvas'), {
// The map is centered on Praia in Cape Verde. I like Cape Verde.
center: new google.maps.LatLng(14.914, -23.517),
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP,
scaleControl: true,
});
// Add a listener to click events on the map. When you click on the map, the click event
// is sent to the function with the latitude and longitude of the click. This is
// converted into a long and short Open Location Code, and displayed under the map.
map.addListener('click', mapClick);
// Display the Open Location Code for a map click event.
function mapClick(event) {
var fullCode = OpenLocationCode.encode(event.latLng.lat(), event.latLng.lng());
// Now we have the full code, let's get the short version by dropping the first four characters.
var shortCode = fullCode.substr(4);
// Build the message for the display. We are not even going to display the full code - because it's
// too long to be useful or memorable. It's...