Google map api with Rails
In this article we are going to learn how we can add simple google map with markers in our rails project.
first of all we need to generate Api key to use google map in the project that we can generate from google developer console using the below link
https://console.cloud.google.com/
we also need to have billing account to use the google map google give $300 for free.
then go to creditional and generate the api key.
after that you need to click on edit API key to restrict the api key so other user can not use your key or your key should only be used by your project.
once you have the key google dashboard part is done.
Get Umeriqbal’s stories in your inbox
Join Medium for free to get updates from this writer.
Now go to rails project and add api key in body tag of application.html.erb using <script> tag.
<!DOCTYPE html>
<html>
<head>
<title>AjaxDataTableExample</title>
<meta name="viewport" content="width=device-width,initial-scale=1">
<%= csrf_meta_tags %>
<%= csp_meta_tag %>
<script src="https://maps.googleapis.com/maps/api/js?key=your_api_key"></script>
<%= stylesheet_link_tag "application", "data-turbo-track": "reload" %>
<%= javascript_include_tag "application", "data-turbo-track": "reload", type: "module" %>
</head>
<body>
<%= yield %>
</body>
</html>As i am using stimulus js so i create google_map_controller.js for to add google map library. here is how our view will look like where we want to add google map. I am adding in index file of google_map you can add it in any file
index.html.erb
<h1>google map</h1>
<div data-controller="google-map">
<div id="map" style="width:100%;height:calc(100vh - 116px);;" data-google-map-target="myMap"></div>
</div>here is our google_map_controller.js will look like
import {Controller} from "@hotwired/stimulus"
// Connects to data-controller="google-map"
export default class extends Controller {
static targets = ['myMap', 'lat', 'lng', 'locationName']
connect() {
let lat = 34.87
let lng = -111.82
//this.latTarget.value = lat
//this.lngTarget.value = lng
this.initMap(lat, lng)
}
async initMap(lat, lng) {
// The location of Uluru
const position = {lat: lat, lng: lng};
let mapId = this.myMapTarget
const {Map} = await google.maps.importLibrary("maps");
// const { AdvancedMarkerElement } = await google.maps.importLibrary("marker");
let map = new Map(mapId, {
center: position,
zoom: 10,
mapId: mapId
});
// The marker, positioned at Uluru
// const marker = new AdvancedMarkerElement({
// map: map,
// position: position,
// title: "Uluru",
// });
this.addSingleMarker(position, map)
// this.addMultipleMarker(map)
}
addSingleMarker(position, map) {
const marker = new google.maps.Marker({
position,
map,
title: `This is single marker`,
label: `1`,
});
marker.setAnimation(google.maps.Animation.BOUNCE); //bouncing animation of marker
}
updateCordinate() {
if (event.currentTarget.dataset.googleMapTarget = 'lat') {
this.initMap(parseFloat(event.currentTarget.value), parseFloat(this.lngTarget.value))
} else {
this.initMap(parseFloat(this.latTarget.value), parseFloat(event.currentTarget.value))
}
}
}we give latitude and longitude in our connect method from where we want to open our map when it load and then pass that value to initMap(lat, lng) method in that method we import the google map library using
const {Map} = await google.maps.importLibrary("maps");then set the position and zoom level in new map object, zoom 0 is the zoom out and zoom 10 will be zoom in if we not give map id it will be ok we give map id in case of multiple markers on the same map.
let map = new Map(mapId, {
center: position,
zoom: 10,
mapId: mapId
});then using the addSingleMarker(position, map) function we are adding the single marker on the map and the last line in addSingleMarker function will animate the marker in the form of bouncing.
Add multiple marker on the map: here is how you can add multiple marker on the map
addMultipleMarker(map) {
const tourStops = [
[{lat: 34.8791806, lng: -111.8265049}, "Boynton Pass"],
[{lat: 34.8559195, lng: -111.7988186}, "Airport Mesa"],
[{lat: 34.832149, lng: -111.7695277}, "Chapel of the Holy Cross"],
[{lat: 34.823736, lng: -111.8001857}, "Red Rock Crossing"],
[{lat: 34.800326, lng: -111.7665047}, "Bell Rock"],
];
// The marker, positioned at Uluru
tourStops.forEach(([position, title], i) => {
const marker = new google.maps.Marker({
position,
map,
title: `${i + 1}. ${title}`,
label: `${i + 1}`,
});
});
}here is how your map will look like in case of multiple markers
here is full documentation related to google map api that is all about the google map Api
Geocode API for google addresses:
to search address by google we can add google geocode API in our js file like this
locationSearch(){
// var address = "1600 Amphitheatre Parkway, Mountain View, CA";
let addressField = event.currentTarget
var address = addressField.value;
let that = this
// Make a request to the Geocoding API
console.log(address)
if(address != ''){
fetch(`https://maps.googleapis.com/maps/api/geocode/json?address=${encodeURIComponent(address)}&key=yourApiKey`)
.then(response => response.json())
.then(data => {
// Extract the latitude and longitude from the response
console.log(data.results[0])
if (data.results[0] != undefined){
var location = data.results[0].geometry.location;
var lat = location.lat;
var lng = location.lng;
console.log("Latitude:", lat);
console.log("Longitude:", lng);
that.initMap(lat, lng)
that.locationNameTarget.innerHTML = data.results[0].formatted_address
that.lngTarget.value = lng
that.latTarget.value = lat
}
})
.catch(error => {
console.error("Error:", error);
});
}
}here is how your view will look like in this case
<h1>google map</h1>
<div data-controller="google-map">
<div class="filter">
<div>
<label>lat: </label>
<input type="text" data-action="keyup->google-map#updateCordinate" data-google-map-target='lat'>
</div>
<div>
<label>lng: </label>
<input type="text" data-action="keyup->google-map#updateCordinate" data-google-map-target='lng'>
</div>
<div>
<label>location: </label>
<input type="text" data-action="keyup->google-map#locationSearch" >
</div>
</div>
<div class="location-name-wrapper">
<span data-google-map-target='locationName'></span>
</div>
<div id="map" style="width:100%;height:calc(100vh - 116px);;" data-google-map-target="myMap"></div>
</div>now update your Coordinate method that we see in our first js that we added, will update the coordinate of the map and marker at run time when you search location.









