Using Tiled Google Map With OpenLayers 3

只愿长相守 提交于 2019-12-06 09:33:44

问题


How can I use google map with OpenLayers 3?
I want to migrate from OpenLayers 2 to 3. here is an example: google map integration with OpenLayers example
but using this method needs to change the old HTML code (two element needs, 'gmap' and 'olmap' that mentioned in the example).
Google Maps is officially not supported by ol3, but my question is:
"How can I use Google Maps Tile Service in my project like a MapServer, without needing to add google API reference (for optimizing purposes) to the scripts tag?"

Here is my old code that works correctly with OpenLayers 2:

var map = new OpenLayers.Map("map_canvas", {
    controls: [
        new OpenLayers.Control.PanZoomBar(),
        new OpenLayers.Control.ScaleLine(),
        new OpenLayers.Control.MousePosition(),
        new OpenLayers.Control.OverviewMap()
    ],
    units: "m",
    numZoomLevels: 21
});
var gmap = new OpenLayers.Layer.Google(
    { type: google.maps.MapTypeId.ROADMAP, numZoomLevels: 21}
);
map.addLayers([gmap]);

and html code:

<div id="map_canvas">
</div>

appreciate any help.


回答1:


I found the solution:

JsFiddle

var map = new ol.Map({
  target: 'map',
  layers: [
    new ol.layer.Tile({
        source: new ol.source.OSM({
            url: 'http://mt{0-3}.google.com/vt/lyrs=m&x={x}&y={y}&z={z}',
            attributions: [
                new ol.Attribution({ html: '© Google' }),
                new ol.Attribution({ html: '<a href="https://developers.google.com/maps/terms">Terms of Use.</a>' })
            ]
        })
    })
  ],
  view: new ol.View({
    center: ol.proj.transform(
        [-110, 45], 'EPSG:4326', 'EPSG:3857'),
    zoom: 3
  })
});
html, body, #map {
    padding: 0;
    margin: 0;
    width: 100%;
    height: 100%;
}
<link href="http://openlayers.org/en/master/css/ol.css" rel="stylesheet"/>
<script src="http://openlayers.org/en/master/build/ol.js"></script>
<div id="map"></div>

but I'm not sure that this code is in contrast with the Google Terms of Use or not.



来源:https://stackoverflow.com/questions/33983656/using-tiled-google-map-with-openlayers-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!