DEV Community

realNameHidden
realNameHidden

Posted on

How to show google map in Spring Boot Application

watch the video

step1 : get google map api key

go to below site

https://console.cloud.google.com/getting-started

choose select a project

Image description

click on new project

Image description

give project name

Image description

Image description

select created project

Image description

Image description

Image description

Image description

choose maps js api

Image description

click on enable

Image description

now its time to create api key

choose credentials

Image description

click on create credentials

Image description

choose api key

Image description

click on show key you can see the key
you can use this key in your app

Image description

next step

create spring boot app with dependencies

lombok , spring web , thymeleaf

Image description

Create MapController.java in controller package

also create index.html in templates folder

Directory Structure

Image description

index.html

Note : Make sure
"mapsApiKey": "you_api_key_that_you_created"
you should give your api key at this place in index.html "you_api_key_that_you_created"

<html>
  <head>
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <script type="text/javascript">
      google.charts.load("current", {
        "packages":["map"],
        // Note: you will need to get a mapsApiKey for your project.
        // See: https://developers.google.com/chart/interactive/docs/basic_load_libs#load-settings
        "mapsApiKey": "you_api_key_that_you_created"
      });
      google.charts.setOnLoadCallback(drawChart);
      function drawChart() {
        var data = google.visualization.arrayToDataTable([
          ['Lat', 'Long', 'Name'],
          [19.0760,  72.8777, 'Mumbai'],
          [18.5204, 73.8567, 'Pune'],
          [19.1176, 72.9060, 'Powai'],
        ]);

        var map = new google.visualization.Map(document.getElementById('map_div'));
        map.draw(data, {
          showTooltip: true,
          showInfoWindow: true
        });
      }

    </script>
  </head>

  <body>
    <div id="map_div" style="width: 800px; height: 700px"></div>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

MapController.java

package com.example.demo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class MapController {

    @GetMapping("/showMap")
    public String index() {
        return "index";
    }
}

Enter fullscreen mode Exit fullscreen mode

Now run the application

give url
http://localhost:8080/showMap
in browser

you will see result as below

Image description

if you want to remove the "for development only " you must enable billing account

Image description

Top comments (0)