Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <html>

<head>
    <title>OpenLayers5 Sample</title>

    <!-- GoogleMapsAPI-->
    <!-- {YOURKEY}へ自分のGoogleMapApiKeyを設定してください -->
    <script src="https://maps.googleapis.com/maps/api/js?key={YOURKEY}"></script>

    <!-- OpenLayers系 -->
    <link rel="stylesheet" href="https://openlayers.org/en/v5.0.0/css/ol.css" type="text/css">
    <script src="https://openlayers.org/en/v5.0.0/build/ol.js"></script>

    <!-- その他 -->
    <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
        crossorigin="anonymous"></script>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" type="text/css">

</head>

<body>
    <div class="container">

        <h2>
            OpenLayers5 Sample
        </h2>

        <!-- ポップアップ用 -->
        <div id="popup" class="ol-popup">
            <a href="#" id="popup-closer" class="ol-popup-closer"></a>
            <div id="popup-content"></div>
        </div>

        <!--
            - olmap: OpenLayers描画用のdiv
            - gogmap: GoogleMaps描画用のdiv

            gogmapの上にolmapを乗せている
        -->
        <div class="map-base bind">
            <div class="map ol bind" id="olmap"></div>
            <div class="map gog bind" id="gogmap"></div>
        </div>

        <div class="bind btns">
            <span class="badge badge-light">
                GoogleMap
            </span>
            <div class="btn-group btn-group-sm">
                <button type="button" class="btn btn-primary" id="btnGogROAD">地図</button>
                <button type="button" class="btn btn-primary" id="btnGogTERR">地形</button>
                <button type="button" class="btn btn-primary" id="btnGogSATE">航空</button>
                <button type="button" class="btn btn-primary" id="btnGogHYBR">地図+航空</button>
            </div>
        </div>

        <div class="bind btns">
            <span class="badge badge-light">
                その他Map
            </span>
            <div class="btn-group btn-group-sm">
                <button type="button" class="btn btn-secondary" id="btnMapOSM">OpenStreetMap</button>
                <button type="button" class="btn btn-secondary" id="btnMapGSI">地理院</button>
            </div>
        </div>

    </div>
</body>

</html>
              
            
!

CSS

              
                
.bind {
    width: 100%;
    height: 100%;
}

.btns {
    text-align: left;
    margin-top: 2px;
}

.container {
    width: 700px;
    text-align: center;
}

.map-base {
    position: relative;
    height: 400px;
    margin: 2px;
}

.map {
    position: absolute;
    top: 0px;
}

.gog {
    z-index: 1;
}

.ol {
    z-index: 2;
}

.ol-popup {
    position: absolute;
    background-color: white;
    filter: drop-shadow(0 1px 4px rgba(0,0,0,0.2));
    padding: 15px;
    border-radius: 10px;
    border: 1px solid #cccccc;
    bottom: 12px;
    left: -50px;
    min-width: 280px;
    font-size: 9px;
  }
  .ol-popup:after, .ol-popup:before {
    top: 100%;
    border: solid transparent;
    content: " ";
    height: 0;
    width: 0;
    position: absolute;
    pointer-events: none;
  }
  .ol-popup:after {
    border-top-color: white;
    border-width: 10px;
    left: 48px;
    margin-left: -10px;
  }
  .ol-popup:before {
    border-top-color: #cccccc;
    border-width: 11px;
    left: 48px;
    margin-left: -11px;
  }
  .ol-popup-closer {
    text-decoration: none;
    position: absolute;
    top: 2px;
    right: 8px;
  }
  .ol-popup-closer:after {
    content: "✖";
  }

              
            
!

JS

              
                
// 地理院のタイルURL <https://maps.gsi.go.jp/development/ichiran.html>
const URL_GSI = "https://cyberjapandata.gsi.go.jp/xyz/std/{z}/{x}/{y}.png";

// 初期値
const INIT_CENTER = { lng: 139.701636, lat: 35.658034 }; // 表示位置 => 渋谷駅
const INIT_ZOOM = 12;

var olmap, gogmap;
var olView;

var makerLayer;

var overlay;

var layer = {
    osm: null,  // OpenStreetMap
    gsi: null   // 地理院
};

window.onload = () => {

    container = document.getElementById('popup');
    content = document.getElementById('popup-content');
    closer = document.getElementById('popup-closer');

    // 初期処理
    createLayers();
    initMap();
    initButton();

    // 初期表示はOpenStreetMap
    switchOlLayersVisible(layer.osm);

    closer.onclick = function() {
        overlay.setPosition(undefined);
        closer.blur();
        return false;
    };
}

// OpenLayersを用いて描画するレイヤーの作成
function createLayers() {

    // OpenStreetMap
    layer.osm = new ol.layer.Tile({
        source: new ol.source.OSM()
    });

    // 地理院
    layer.gsi = new ol.layer.Tile({
        source: new ol.source.XYZ({
            url: URL_GSI
        })
    });
}

// 各Mapの初期化
function initMap() {

    overlay = new ol.Overlay({
        element: container,
        autoPan: true,
        autoPanAnimation: {
            duration: 250
        }
    });

    // OpenLayersの初期化
    olmap = new ol.Map({
        target: "olmap",
        layers: [
            layer.osm,
            layer.gsi
        ],
        controls: ol.control.defaults({
        }).extend([
            new ol.control.ScaleLine()
        ]),
        view: new ol.View({
            center: ol.proj.fromLonLat([INIT_CENTER.lng, INIT_CENTER.lat]),
            zoom: INIT_ZOOM
        }),
        overlays: [overlay],
    });

    olmap.on('singleclick', function(evt) {
        let coordinateTf = ol.proj.transform(evt.coordinate, 'EPSG:3857', 'EPSG:4326');
        coordinateTf[0] = coordinateTf[0].toFixed(3);
        coordinateTf[1] = coordinateTf[1].toFixed(3);

        content.innerHTML = "<code>" + coordinateTf + "</code>";
        overlay.setPosition(evt.coordinate);
    });

    // GoogleMapの初期化
    gogmap = new google.maps.Map(document.getElementById("gogmap"), {
        center: INIT_CENTER,
        zoom: INIT_ZOOM,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        mapTypeControlOptions: {
            mapTypeIds: [
                google.maps.MapTypeId.ROADMAP,
                google.maps.MapTypeId.TERRAIN,
                google.maps.MapTypeId.SATELLITE,
                google.maps.MapTypeId.HYBRID
            ]
        },
        mapTypeControl: false,
        streetViewControl: false,
        zoomControl: false,
        scaleControl: false,
        rotateControl: false,
        fullscreenControl: false,
        visible: false
    });

    olView = olmap.getView();

    // OpenLayersとGoogleMapの連携
    //  地図移動
    olView.on("change:center", () => {
        var center = ol.proj.transform(olView.getCenter(), 'EPSG:3857', 'EPSG:4326');
        gogmap.setCenter({ lng: center[0], lat: center[1] });
    });
    //  ズーム
    olView.on("change:resolution", () => {
        gogmap.setZoom(olView.getZoom());
    });
}

// ボタン初期化(イベント)
function initButton() {

    // GoogleMap系
    $("#btnGogROAD").on("click", () => { switchGogMapType(google.maps.MapTypeId.ROADMAP) });
    $("#btnGogTERR").on("click", () => { switchGogMapType(google.maps.MapTypeId.TERRAIN) });
    $("#btnGogSATE").on("click", () => { switchGogMapType(google.maps.MapTypeId.SATELLITE) });
    $("#btnGogHYBR").on("click", () => { switchGogMapType(google.maps.MapTypeId.HYBRID) });

    // OpenStreetMap
    $("#btnMapOSM").on("click", () => {
        switchOlLayersVisible(layer.osm);
    });

    // 地理院
    $("#btnMapGSI").on("click", () => {
        switchOlLayersVisible(layer.gsi);
    });

    // マーカー:恵比寿
    $("#btnMakerEbisu").on("click", () => {
        if(makerLayer != undefined && makerLayer != null) {
            olmap.removeLayer(makerLayer);
        }

        let iconStyle = new ol.style.Style({
            image: new ol.style.Icon({
                src: "free_maker.png",
            })
        });

        let iconFeature = new ol.Feature(ol.proj.fromLonLat([INIT_CENTER.lng, INIT_CENTER.lat]));
        iconFeature.setStyle(iconStyle);
        
        let vectorSource = new ol.source.Vector();
        vectorSource.addFeature(iconFeature);
        makerLayer = new ol.layer.Vector({
            source: vectorSource,
            style: iconStyle,
        });
        olmap.addLayer(makerLayer);
    });
}

// GoogleMapの地図タイプを切り替える
function switchGogMapType(id) {
    gogmap.setMapTypeId(id);
    switchOlLayersVisible();
}

// OpenLayersの表示するレイヤーを切り替える
function switchOlLayersVisible(currentLayer) {

    if (currentLayer == undefined || currentLayer == null) {
        $("#gogmap").show();
    } else {
        $("#gogmap").hide();
    }

    olmap.getLayers().getArray().forEach((item) => {
        item.setVisible(currentLayer === item);
    });
}


              
            
!
999px

Console