Real-time Google Map Embedding Using Vue JS


Everybody is familiar with embedding the google map on their sites especially on the contact page. In this tutorial, I will show you how to create a simple real-time google map embedding using Vue js. The application will also give real time geographics coordinates too. Besides Vue js,  I will also use Axios for making HTTP API request and Lodash for easily adding extra functionality in javascript.

The application will accept place name and it will call Google Map API in real time to get both latitude and longitude of the place you search for and also embed the map of that place. Before we start coding we need to get our free Google Map API Key. You can grab your free key by visiting the following link.

We are using two Google Map REST API in this demo application.

1) Google Maps Embed API

The Google Maps Embed API lets you place an interactive map, or Street View panorama on your site with a simple HTTP request. It can be easily embedded on your web page or blog by setting the Google Maps Embed API URL as the src attribute of an iframe:

<iframe width="600" height="450" frameborder="0" style="border:0"
  src="https://www.google.com/maps/embed/v1/place?key=YOUR_API_KEY&q=Space+Needle,Seattle+WA" allowfullscreen>
</iframe>

 

2) Geocoding request and response (latitude/longitude lookup) API

The following example requests the latitude and longitude of "1600 Amphitheatre Parkway, Mountain View, CA", and specifies that the output must be in JSON format.

https://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&key=YOUR_API_KEY

You can test this by entering the URL into your web browser (be sure to replace ‘YOUR_API_KEY’ with your actual API key). The response includes the latitude and longitude of the address.

Let's Start Coding

The Complete code of the view page is given below.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
    <title>Vue Js Demo</title>

    <!-- Bootstrap -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" > 
    
    <link rel="stylesheet" type="text/css" href="style.css">

  </head>
  <body>
    <div id="app">
      <div class="container">
        <div class="row">
          <div class="col-md-10 col-md-offset-1">
            <div class="lead-form">
              <h1 class="text-center">Real-time Google Map Embedding - Vue JS 2</h1>
              <hr/>
              <div class="row">
                <div class="col-md-12">
                  <input type="text" class="form-control input-lg" placeholder="Enter Place Name" v-model="place">
                </div>
                <div class="col-md-6"><h3> Latitude : {{ latitude }}</h3></div>
                <div class="col-md-6"><h3> Longitude : {{ longitude }}</h3></div>
                <div class="col-md-12"  v-bind:class="{ 'not-visible' : active }" >
                    <iframe frameborder="0" style="width: 100%; height: 350px; border:0" v-bind:src="'https://www.google.com/maps/embed/v1/place?key=YOUR_API_KEY&q='+ place" allowfullscreen></iframe>
                </div>
              </div>
            </div><!-- end of .lead-form -->
          </div> <!-- end of .col-md-6.col-md-offset-3 -->
        </div> <!-- end of .row -->
      </div> <!-- end of .container -->
    </div> <!-- end of #app -->
  </body>
  <script src="https://unpkg.com/vue@2.0.3/dist/vue.js"></script>
  <script src="https://unpkg.com/axios@0.12.0/dist/axios.min.js"></script>
  <script src="https://unpkg.com/lodash@4.13.1/lodash.min.js"></script>
  <script type="text/javascript" src="main.js"></script>
</html>

 

The input is two-way bound to a model named the place. The both latitude and longitude models are one-way bound. The active model is used to make the visibility of iframe hidden when there is no value in input. I used some bootstrap for creating a very basic CSS layout.

Now let's see the codes inside the main.js file.

var app = new Vue({
  el: '#app',
  data: {
    place: '',
    latitude: '',
    longitude: '',
    active : true
  },
  watch: {
    place: function() {
      this.latitude = '';
      this.longitude = '';
      this.active = true;
      if (this.place.length >= 3) {
        this.active = false;
        this.lookupCoordinates();
      }
    }
  },
  methods: {
    lookupCoordinates: _.debounce(function() {
      var app = this;
      app.latitude = "Searching...";
      app.longitude = "Searching...";
      axios.get('https://maps.googleapis.com/maps/api/geocode/json?address=' + app.place)
            .then(function (response) {
              app.latitude = response.data.results[0].geometry.location.lat;
              app.longitude = response.data.results[0].geometry.location.lng;
            })
            .catch(function (error) {
              app.latitude = "Invalid place";
              app.longitude = "Invalid place";
            })
    }, 500)
  }
})

 

The watch is used to ensure that the API call only happens when there is at-least 3 character in our input field. It helps to reduce unwanted API calls. When input length reaches 3 letters then the lookupCoordinates method is called. The _.debounce() is a lodash custom method which is used to delay the execution to 500 milliseconds so that it will give the user to completely type their place name and thus prevent unwanted API calls. The axios.get() method call the google map API for getting geolocation information such as latitude and longitude. The axios.then() method gives us the response JSON data and we bind it to our latitude and longitude models. The axios.catch() catches the errors. 

Now finally let's improve the look and feel of our application. The codes in the style.css file are given below.

#app {
  height: 100%;
  width: 100%;
  background-color: red;
  background: url("https://source.unsplash.com/category/nature/1920x1080") no-repeat center center fixed;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
}

h1,h3{
  font-weight: bold;
  color: #666666;
}

.not-visible{
  visibility: hidden;
}

#submit-form {
  margin-top: 20px;
}

.lead-form {
  background-color: rgba(255, 255, 255, 0.6);
  border-radius: 5px;
  padding: 10px 50px 30px 50px;
  margin-top: 30px;
  margin-bottom: 30px;
}

span.city-span {
  color: (#444);
  text-transform: uppercase;
  margin-left: 5px;
  margin-top: 10px;
}

.form-control {
  margin-bottom: 3px;
}

 

I am using Unsplash Source API for getting free beautiful different photos every time I refresh the page. You can customize it by visiting the following link.

The output image of above program is given below.

 Real-time Google Map Embedding  Vue JS Demo

DEMO

You can demo the above code by visiting following link.

https://shareurcodes.com/demo/vmap/

If anybody has any suggestions or doubts or need any help comment below and I try will respond to every one of you as early as possible.





Web development
30 Jul 2017 06:39pm
Javascript Ajax Vue.js
143