I am new using OpenLayers (an open-source JavaScript library for displaying map data in web browsers as slippy maps). I am using it with Thymeleaf (a Java XML/XHTML/HTML5 template engine that can work both in web and non-web environments).
I am trying to reproduce this example, but getting the resources from the server https://openlayers.org/en/latest/examples/reprojection-wgs84.html
I have this page:
<!doctype html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<title>Title</title>
<script src="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io#master/en/v6.3.1/build/ol.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io#master/en/v6.3.1/css/ol.css">
<style>
.map {
width: 100%;
height:400px;
}
</style>
</head>
<body>
<div id="layout">
<div id="main">
<div class="content">
<div class="pure-g">
<div class="pure-u-1-1 pure-u-xl-10-24 pure-u-med-1">
<!-- Content right Wrap -->
<div class="content_r_wrap">
<!-- Devices Map Module -->
<div class="windowHead">
<h2>LOCATION INFO</h2>
</div>
<div class="windowContentMap">
<div id="map" class="map"></div>
<script th:inline="javascript" th:type="module">
/*<![CDATA[*/
import Map from '/css/Map';
import View from '/css/View';
import TileLayer from '/css/layer/Tile';
import OSM from '/css/source/OSM';
var map = new Map({
layers: [
new TileLayer({
source: new OSM()
})
],
target: 'map',
view: new View({
projection: 'EPSG:4326',
center: [0, 0],
zoom: 2
})
});
/*]]>*/
</script>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
and I would like to know how to get those objects also from the server:
import Map from '/css/Map';
import View from '/css/View';
import TileLayer from '/css/layer/Tile';
import OSM from '/css/source/OSM';
Not sure what mean but if "getting from the server" means accessing the imports directly from a compiled source (be it on your server or elsewhere), this is how to do it:
const Map = window.ol.Map;
const View = window.ol.View;
const TileLayer = window.ol.layer.Tile;
const OSM = window.ol.source.OSM;
var map = new Map({
layers: [
new TileLayer({
source: new OSM()
})
],
target: 'map',
view: new View({
projection: 'EPSG:4326',
center: [0, 0],
zoom: 2
})
});
<link href="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io#master/en/v6.3.1/css/ol.css" rel="stylesheet"/>
<script src="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io#master/en/v6.3.1/build/ol.js"></script>
<style>
.map {
width: 100%;
height: 400px;
}
</style>
<div id="layout">
<div id="main">
<div class="content">
<div class="pure-g">
<div class="pure-u-1-1 pure-u-xl-10-24 pure-u-med-1">
<!-- Content right Wrap -->
<div class="content_r_wrap">
<!-- Devices Map Module -->
<div class="windowHead">
<h2>LOCATION INFO</h2>
</div>
<div class="windowContentMap">
<div id="map" class="map"></div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
When you are calling
<script src="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io#master/en/v6.3.1/build/ol.js"></script>
you actually get the built file from CDN (I guess, "the server" you talked about).
So, in that file you can access the modules Map, View, TileLayer, OSM etc... All as a result of the import of the script from CDN.
If you want to load these files from your local project, which can be "offline", you can install them using Package Manager (like NPM) or just download the bundled (built) files (css and js), save them in a directory you could access to, and change your source to the directory.
My recommendation (and also OpenLayer's) is using npm and then use it regularly (import ol):
index.js
import 'ol/ol.css';
import {Map, View} from 'ol';
import TileLayer from 'ol/layer/Tile';
import OSM from 'ol/source/OSM';
const map = new Map({
target: 'map',
layers: [
new TileLayer({
source: new OSM()
})
],
view: new View({
center: [0, 0],
zoom: 0
})
});
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Using Parcel with OpenLayers</title>
<style>
#map {
width: 400px;
height: 250px;
}
</style>
</head>
<body>
<div id="map"></div>
<script src="./index.js"></script>
</body>
</html>
In that case, OpenLayer's files are INSTALLED in your project inside node_modules and you are no longer dependent on external network traffic to the CDN.
That's it :)
You can follow the complete guide here (they explain there how to bundle and run the program):
OpenLayers using NPM
Related
Can anyone help in resolving this issue?, I am trying to create a map showing map markers of power plants in the US and also a heatmap later on. The problem with my code is that my map is not even showing when it goes live. I have attached the config, location and index files to help with finding the issue. I initially had a local csv file, which I converted to geojson which was then deployed on github.
config.js
// API key
const API_KEY = "pk.eyJ1IjoidGF1cmVhbmgiLCJhIjoiY2tmb21yc2tzMDFnYTJ0bXVuMzVub2tvYyJ9.vhUstehmvTj6HgfalepX8w";
location.js
var myMap = L.map("map", {
center: [37.7749, -122.4194],
zoom: 13
});
// Adding tile layer
L.tileLayer("https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token={accessToken}", {
attribution: "© <a href='https://www.mapbox.com/about/maps/'>Mapbox</a> © <a href='http://www.openstreetmap.org/copyright'>OpenStreetMap</a> <strong><a href='https://www.mapbox.com/map-feedback/' target='_blank'>Improve this map</a></strong>",
tileSize: 512,
maxZoom: 18,
zoomOffset: -1,
id: "mapbox/streets-v11",
accessToken: API_KEY
}).addTo(myMap);
var url = "https://taureanh.github.io/geojson/";
d3.json(url, function(response) {
console.log(response);
for (var i = 0; i < response.length; i++) {
var geometry = response[i].geometry;
if (geometry) {
L.marker([geomtery.coordinates[1], geometry.coordinates[0]]).addTo(myMap);
}
}
});
index.html
<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="UTF-8">
<title>Map Markers</title>
<!-- Leaflet CSS -->
<link rel="stylesheet" href="https://unpkg.com/leaflet#1.3.3/dist/leaflet.css" integrity="sha512-Rksm5RenBEKSKFjgI3a41vrjkw4EVPlJ3+OiI65vTjIdo9brlAacEuKOiQ5OFh7cOI1bkDwLqdLw3Zg0cRJAAQ==" crossorigin="" />
<!-- Our CSS -->
<link rel="stylesheet" href="./static/css/style.css" />
</head>
<body>
<div id="map"></div>
<!-- API key -->
<script type="text/javascript" src="static/js/config.js"></script>
<!-- Leaflet JS -->
<script src="https://unpkg.com/leaflet#1.3.3/dist/leaflet.js" integrity="sha512-tAGcCfR4Sc5ZP5ZoVz0quoZDYX5aCtEm/eu1KhSLj2c9eFrylXZknQYmxUssFaVJKvvc0dJQixhGjG2yXWiV9Q==" crossorigin=""></script>
<!-- D3 CDN -->
<script src="https://d3js.org/d3.v4.min.js"></script>
<!-- JS -->
<script type="text/javascript" src="static/js/location.js"></script>
<!-- <script type="text/javascript" src="static/js/heatmap.js"></script> -->
<!-- Leaflet heatmap plugin-->
<script type="text/javascript" src="static/js/leaflet-heat.js"></script>
</body>
</html>
d3.json expects JSON, but your endpoint is returning HTML:
curl -I https://taureanh.github.io/geojson/
HTTP/2 200
server: GitHub.com
content-type: text/html; charset=utf-8
You should update your endpoint so that is actually returns JSON: content-type: application/json; just data, no <html> tags.
Alternatively, you could update location.js to get the endpoint (d3.request(url, function(html)), then parse the response into JSON yourself (strip the html tags, then use JSON.parse). This will work, but it's messy and not ideal.
Found this Free webiste online that i want to customize but i cant change the default zoom lvl, i dont know javascript. I would like to know what lines of code i need to add in order to change the zoom lvl.
Thanks, :=),
also i dont know if i have to include other code/info here, just tell me if you need more info.
<!-- Footer -->
<footer>
<!-- Container -->
<div class="container">
<div class="row">
</div>
</div><!-- Container end -->
</footer><!-- Footer end -->
<!-- scroll up-->
<div class="scrollup">
<i class="fa fa-chevron-up"></i>
</div><!-- End off scroll up->
<!-- JavaScript -->
<script src="http://code.jquery.com/jquery-1.12.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<!-- Bootsnav js -->
<script src="js/bootsnav.js"></script>
<!-- JS Implementing Plugins -->
<script src="http://maps.google.com/maps/api/js?sensor=true"></script>
<script src="js/gmaps.min.js"></script>
<script type="text/javascript">
var map;
$(document).ready(function () {
map = new GMaps({
el: '#ourmaps',
lat: 15,
lng: 15,
scrollwheel: true
});
//locations request
map.getElevations({
locations: [[15, 15]],
callback: function (result, status) {
if (status == google.maps.ElevationStatus.OK) {
for (var i in result) {
map.addMarker({
lat: result[i].location.lat(),
lng: result[i].location.lng(),
infoWindow: {
content: '<address class="tooltip_address"><b>aaaa</b><br />aaa<br />aaaa<br />aaaa <br /></address>'
}
});
}
}
}
});
});
</script>
<!--main js-->
<script type="text/javascript" src="js/main.js"></script>
Try this:
zoom: 8
From documentation.
see This also
you're using Gmaps.js so you will need to find documentation about this javascript, as the webpage says you need to use setZoom that allows an integer of your desired zoom, also you will need to use setCenter to center the map on your desired marker.
Here's the GMaps.js website: GMaps.js
Here's where you cand find all the parameters that allows:
Documentation
You can also set the zoom when you create your Gmaps, so this is the main code you need to edit in your example:
map = new GMaps({
el: '#ourmaps',
lat: 15,
lng: 15,
scrollwheel: true,
zoom: 15 //Your desired zoom
});
Also I find a note on a blog that if you use more than 1 marker you may be using::
map.setZoom((map.getBoundsZoomLevel(bounds))); //To rezoom the map
map.setCenter(bounds.getCenter()); //To center the map
Reference about using more than one marker
Hope my answer helps you!!
my VueJS/Laravel application does not load in GoogleMaps properly as I would expect. I dont understand why the callback is not called. The function is available and it should load. can you help me? I do not find my mistake. I dont expect to see the map yet as I only have a consol.log in the init, but even this is not called. The error message when I open the full google URL is:
The Google Maps API server rejected your request. Invalid request.
Invalid 'callback' parameter.
<script src="https://maps.googleapis.com/maps/api/js?key=KEY&libraries=places,geometry&callback=App.init async defer"></script>
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>INSPINIA - #yield('title') </title>
<link rel="stylesheet" href="{!! asset('css/vendor.css') !!}" />
<link rel="stylesheet" href="{!! asset('css/app.css') !!}" />
</head>
<body>
<!-- Wrapper-->
<div id="wrapper">
<!-- Navigation -->
#include('layouts.navigation')
<!-- Page wraper -->
<div id="page-wrapper" class="gray-bg">
<!-- Page wrapper -->
#include('layouts.topnavbar')
<!-- Main view -->
#yield('content')
<!-- Footer -->
#include('layouts.footer')
</div>
<!-- End page wrapper-->
</div>
<!-- End wrapper-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.0/vue.min.js"></script>
<script src="{!! asset('js/app.js') !!}" type="text/javascript"></script>
<script src="{!! asset('js/main.js') !!}" type="text/javascript"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=KEY&libraries=places,geometry&callback=App.init async defer"></script>
#section('scripts')
#show
</body>
</html>
Main JS
const GISView = require('./components/GISView.vue');
window.Vue = Vue;
window.Event = new class {
constructor() {
this.Vue = new Vue();
}
fire(event, data = null) {
this.Vue.$emit(event, data);
}
listen(event, callback) {
this.Vue.$on(event, callback);
}
};
var App = window.App = new Vue({
el: '#app',
components: {
GISView: GISView
},
data: {},
methods: {
init: function() {
console.log("OK");
}
}
});
GIS VUE
<template>
<div id="map"></div>
</template>
<script>
import GoogleMaps from '../mixins/GoogleMaps.js';
export default {
mixins: [GoogleMaps],
data: {
test: 1
},
mounted() {
this.initMap();
},
methods: {
initMap: function() {
this.map = new google.maps.Map(document.getElementById('map'), {
center: { lat: 83.298, lng: 35.555},
scollwheel: false,
zoom: 4
})
}
}
}
</script>
#map {height:300px;width:500px;}
Change
<script src="https://maps.googleapis.com/maps/api/js?key=KEY&libraries=places,geometry&callback=App.init async defer"></script>
To
<script src="https://maps.googleapis.com/maps/api/js?key=KEY&libraries=places,geometry&callback=App.init" async defer ></script>
And please make sure your API key is not KEY ;)
The only change is moving the async and defer to outside of the API URL
I'm trying to use the Google Maps API to get a single map to show. I'm using Javascript.
It should be a single page with one header and one map below the header. I signed up for the Google Maps API recently, so I'm not sure if it takes a certain amount of time for the API key to be active or not. I've got other CSS files and a googlemaps.js file that doesn't have anything in it yet.
Here's my code. Any ideas why it's not working?
<!doctype html>
<html>
<head>
<meta charset='utf-8'>
<meta name='viewport' content='width=device-width, intial-scale=1.0;'>
<title>API(s)</title>
<link rel='stylesheet' href='styles/semantic.min.css'>
<link rel='stylesheet' href='styles/main.css'>
</head>
<body>
<div class="ui two column centered stackable grid container">
<div class="column">
<h1 class="goog-header">Location Based Image Search</h1>
</div>
</div>
<div class="ui one column stackable grid container js-images-container">
<div class="column">
<div id="map"></div>
</div>
</div>
<script>
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 8
});
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCXTmorapOu1WquB3VlsLrckhE45Bgfrfw&callback=initMap" async defer></script>
<script src='javascript/googlemaps.js'></script>
</body>
</html>
Try to change your map DIV to:
<div id="map" style="width:800px;height:600px"></div>
I am having trouble loading a google map, while using angular routes with a template. As the code currently stands if i navigate to "#/map" the google map does not show up and inspecting the element, the map information is not there but the template loads as the h1 tag 'Map' does load. However, if I take the code from my map template and put it into my index.html it works perfectly fine. Does anyone know why this is and how to fix it?
Here is my index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Ski</title>
<script src="bower_components/angular/angular.js"></script>
<script src="bower_components/angular-route/angular-route.js"></script>
</head>
<body ng-app="Ski">
<ng-view></ng-view>
<!-- app and routes -->
<script src="js/app.js"></script>
<script src="js/routes.js"></script>
<!-- controllers -->
<script src="js/controllers/map.controller.js"></script>
</body>
</html>
This is my template for map.
<div>
<h1> Map </h1>
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?key=xxxxxxxxxxxxxxxxxxxx">
</script>
<script type="text/javascript">
function initialize() {
var mapOptions = {
center: { lat: -34.397, lng: 150.644},
zoom: 8
};
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<div id="map-canvas" style="width: 50%; height: 50%;"></div>
</div>
My angular module.
angular.module('Ski', ['ngRoute']);
My angular routes.
angular.module('Ski').config(function($routeProvider) {
'use strict';
$routeProvider
.when('/home', {
templateUrl: 'templates/home.html'
})
.when('/map', {
templateUrl: 'templates/map.html'
})
.otherwise({
redirectTo: '/'
});
});
The problem is that when map view is loaded window.load event has already occurred, so this line
google.maps.event.addDomListener(window, 'load', initialize);
won't invoke initialize function, because load event is not going to happen again.
Instead try to move map script into head section:
<head>
<meta charset="utf-8">
<title>Ski</title>
<script src="https://maps.googleapis.com/maps/api/js?key=xxxxxxxxxxxxxxxxxxxx"></script>
<script src="bower_components/angular/angular.js"></script>
<script src="bower_components/angular-route/angular-route.js"></script>
</head>
and then write simple directive to initialize map in map template:
<div>
<h1>Map</h1>
<map-canvas id="map" style="width: 50%; height: 50%;"></map-canvas>
</div>
The mapCanvas directive will look then something like this:
angular.module('Ski').directive('mapCanvas', function() {
return {
restrict: 'E',
link: function(scope, element) {
var mapOptions = {
center: { lat: -34.397, lng: 150.644},
zoom: 8
};
new google.maps.Map(element[0], mapOptions);
}
};
});
Demo: http://plnkr.co/edit/370NBWS3YlTrGBqK7riT?p=preview