简体   繁体   中英

How can i add google map to a component that is using sightly?

I have a component called foo

I have foo.html in apps/foo/components/content/foo/foo.html

currently this file contains the following.

<div  data-sly-use.ev="Foo"
        class="${ev.cssClass || ''}"
        title="${ev.title || ''}"
        data-emptytext="Foo Asset">
        ${ev.html @ context='unsafe'}</div>

I have Foo.java in apps/foo/components/content/foo/Foo.java that has getCssClass(), getTitle(), getHtml() needed by foo.html.

The above works fine

Question

When the user adds this component to the page, I want it to include a google map in the page. The lat/long to the google map will be provided by Foo.java#getLat() and Foo.java#getLong()

How can I do this?

I have the google map working in an HTML outside of AEM and the code is pretty simple:

<!DOCTYPE html>
<html>
  <head>
    <style>
      #map-canvas {
        width: 500px;
        height: 400px;
      }
    </style>
    <script src="https://maps.googleapis.com/maps/api/js"></script>
    <script>
      function initialize() {
        var mapCanvas = document.getElementById('map-canvas');
        var myLatlng = new google.maps.LatLng(-25.363882,131.044922);
        var mapOptions = {
          center: myLatlng,
          zoom: 8,
          mapTypeId: google.maps.MapTypeId.ROADMAP
        }
        var map = new google.maps.Map(mapCanvas, mapOptions)
        var marker = new google.maps.Marker({
          position: myLatlng,
          map: map,
          title: 'Hello World!'
        });
      }
      google.maps.event.addDomListener(window, 'load', initialize);
    </script>
  </head>
  <body>
    <div id="map-canvas"></div>
  </body>
</html>

the lat/long values for myLatlng variable in the above javascript will need to come from Foo.java .

If you want to pass parameters to a script you can do as they generally do in Coral UI via data-xxx attributes in the Sightly script.

  • Set the property from your Foo into a data attribute in some DIV you will later fetch in JS.
  • Get the div in JS via its ID and obtain the data attributes you are interested in.

Example:

Sightly

<div id="map_canvas" data-lat="${ev.lat}" data-long="${ev.long}">
</div>

Javascript

this.mapCanvas = document.getElementsByClassName("map_canvas")[0];
var lat = $mapCanvas.data("lat");
var long = $mapCanvas.data("long");
var myLatlng = new google.maps.LatLng(lat,long);

I hope this helps! :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM