簡體   English   中英

如何在vaadin頁面中集成google-maps?

[英]How to integrate google-maps in a vaadin page?

我想將google-maps嵌入現有的vaadin網頁中。

問題:vaadin是用Java編寫的,因此沒有對htmljavascript行進行編碼。

有一個有關如何使用靜態網頁集成地圖的示例: https : //developers.google.com/maps/documentation/javascript/examples/map-simple

<!DOCTYPE html>
<html>
  <head>
    <title>Simple Map</title>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">

    <script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
    <script>
var map;
function initialize() {
  map = new google.maps.Map(document.getElementById('map-canvas'), {
    zoom: 8,
    center: {lat: -34.397, lng: 150.644}
  });
}

google.maps.event.addDomListener(window, 'load', initialize);

    </script>
  </head>
  <body>
    <div id="map-canvas" />
  </body>
</html>

如您所見,這需要頁面內的<script>內容。

問題:如何使用vaadin包含這些腳本內容? 再加上如何將地理坐標動態傳遞給javascript函數?

(我不想為此使用任何vaadin插件,因為我只是想顯示地圖)。

您可以在vaadin中創建自定義組件,然后在自定義組件的構造函數中調用javascript代碼。 這說起來容易做起來難,因此,您應該這樣做:

Vaadin-UI頁面:

protected void init(VaadinRequest request) {
        /****************************************************
         * Create instance of custom component and set an id
         ***************************************************/
        Map mapobject = new Map();
        mapobject.setId("mapob");
        ..
        ..
        ..
        ..
       }

然后創建一個名為Map.java的新Java類(您的組件),該類應類似於以下內容:

import com.vaadin.annotations.JavaScript;
import com.vaadin.annotations.StyleSheet;
import com.vaadin.ui.AbstractJavaScriptComponent;

@JavaScript({ "myscript.js", "https://maps.googleapis.com/maps/api/js?v=3.exp"})
@StyleSheet({ "mystyle.css" })

//Extend AbstractJavaScriptComponent
public class Map extends AbstractJavaScriptComponent {

    float param1=123;
    float param2=456;
    public Map() {
       callFunction("myfunction",param1,param2); //Pass parameters to your function
    }

}

現在,最后一步是創建已鏈接的js和CSS文件。

創建-> myscript.js和mystyle.css文件

按原樣在CSS中定義所有樣式

在您的JS中,如下定義函數:

window.your_package_name_Map = function() { //Put correct package name

      this.myfunction = function(latitude, longitude) {     //Accept the parameters
         var map;

            //mapob is the id of your component
            map = new google.maps.Map(document.getElementById("mapob"), { 
            zoom: 8,
            center: {lat: latitude, lng: longitude}
              });
            google.maps.event.addDomListener(window, 'load', initialize);
    }
        };

這應該做。 我希望我什么都沒錯過

我真的不明白為什么您不能使用插件,所以您應該使用它:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM