How to Use Google Map API to Your Website

1. Create credenitials API Key

  • Step 1: Access to Google Developers Console.
  • Step 2: Create or select a project.
  • Step 3: Click Continue to Enable the API (Google Maps JavaScript API).
  • Step 4: Go to Credentials to get a Server key (and set the API Credentials).

 

2. Embedded script like this:

<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&signed_in=true&callback=initMap" async defer></script>

 

3. Add initMap method in Javascript

<script>

  function initMap() {

    var hcmCity = {lat: 10.8230989, lng: 106.6296638} ;// default

    var geocoder = new google.maps.Geocoder();

    var map = new google.maps.Map(document.getElementById('map'), {

      zoom: 17,

      center: hcmCity,

      scrollwheel: false

    });

    geocodeAddress(geocoder, map);

    document.getElementById('submit').addEventListener('click', function() {

      geocodeAddress(geocoder, map);

    });

  }

  function geocodeAddress(geocoder, map) {

    var address = document.getElementById('address').value;

    geocoder.geocode({'address': address}, function(results, status) {

      if (status === google.maps.GeocoderStatus.OK) {

        map.setCenter(results[0].geometry.location);

        var marker = new google.maps.Marker({

          title: address,

          map: map,

          scrollwheel: false,

          position: results[0].geometry.location

        });

      } else {

        alert('Geocode was not successful for the following reason: ' + status);

      }

    });

  }

</script>

4. In view

<body>

  <div id="search-panel">

    <input id="address" type="textbox" value="Ho Chi Minh">

    <input id="submit" type="button" value="Geocode">

  </div>

  <div id="map"></div>

</body>

 

5. Demo Geocoding service

 

6. Source code

Code: https://goo.gl/FYNc68

 

7. Reference

Tutorial: https://goo.gl/gn2mKo

Examples: https://goo.gl/ApbWmp