Adding Google Maps dynamically in Spring (MVC or Boot)

Issue

I am developing an application on rental system in Spring Boot. I need help for adding the google map marker(s) dynamically and displaying it for each rooms I add.
For e.g : While adding room details then also saving google map marker for each into MySQL database and displaying it.

Solution

Storing locations for stores is easy, as it is just a class containing latitude and longitude. It could be something like this (for more information, see the guide by Spring):

@Entity
public class Position {

  @Id
  @GeneratedValue(strategy=GenerationType.AUTO)
  private Long id;
  private Long latitude;
  private Long longitude;

  @OneToOne
  private Store store;

  protected Position() {}

  public Position(long latitude, longitude, Store store) {
    this.latitude = latitude;
    this.longitude = longitude;
    this.store = store;
  }

  // Standard Getters and Setters
}

Using this object, you can pass the latitude and longitude to the MVC controller, which should inject the values in the following piece of code (from the Google Documentation):

<div id="map"></div>
<script th:inline="javascript">
  /*<![CDATA[*/
  function initMap() {
    // The location of the map
    var shop = { lat: /*[[${session.shop.latitude}]]*/, lng: /*[[${session.shop.longitude}]]*/ };
    var map = new google.maps.Map(
      document.getElementById('map'), { zoom: 4, center: shop });
    var marker = new google.maps.Marker({ position: shop, map: map });
  }
/*]]>*/
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
</script>

Answered By – Titulum

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published