I am new to GIS and I am working on my openLayer tutorial.
Here is HTML code:
<html>
<head>
<meta charset="utf-8" />
<meta name="format-detection" content="telephone=no" />
<meta name="msapplication-tap-highlight" content="no" />
<!-- WARNING: for iOS 7, remove the width=device-width and height=device-height attributes. See https://issues.apache.org/jira/browse/CB-4323 -->
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />
<link rel="stylesheet" type="text/css" href="css/index.css" />
<title>Hello World</title>
</head>
<body>
<div class="app">
<div style="width:100%; height:100%" id="map"></div>
</div>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<script src="http://openlayers.org/api/OpenLayers.js"></script>
<script type="text/javascript">
app.initialize();
</script>
</body>
</html>
Here is JavaScript code:
var app = {
// Application Constructor
initialize: function () {
//this.bindEvents();
var map = new OpenLayers.Map('map');
var wms = new OpenLayers.Layer.WMS("OpenLayers WMS", "http://vmap0.tiles.osgeo.org/wms/vmap0", { layers: 'basic' });
var dm_wms = new OpenLayers.Layer.WMS(
"Canadian Data",
"http://www2.dmsolutions.ca/cgi-bin/mswms_gmap",
{
layers: "bathymetry,land_fn,park,drain_fn,drainage," +
"prov_bound,fedlimit,rail,road,popplace",
transparent: "true",
format: "image/png"
},
{ isBaseLayer: false }
);
var vectorLayer = new OpenLayers.Layer.Vector("Overlay");
var feature = new OpenLayers.Feature.Vector(
new OpenLayers.Geometry.Point(-71, 4),
{ some: 'data' },
{
externalGraphic: 'img/location_fav.png',
graphicHeight: 21,
graphicWidth: 16
});
vectorLayer.addFeatures(feature);
map.addLayers([wms, dm_wms, vectorLayer]);
map.zoomToMaxExtent();
}
};
View in browser:
I get this error:
http://www2.dmsolutions.ca/cgi-bin/mswms_gmap?LAYERS=bathymetry%2Cland_fn%2…EST=GetMap&STYLES=&SRS=EPSG%3A4326&BBOX=-180,-90,0,90&WIDTH=256&HEIGHT=256 Failed to load resource: net::ERR_NAME_NOT_RESOLVED
If I remove from javascript this rows:
var dm_wms = new OpenLayers.Layer.WMS(
"Canadian Data",
"http://www2.dmsolutions.ca/cgi-bin/mswms_gmap",
{
layers: "bathymetry,land_fn,park,drain_fn,drainage," +
"prov_bound,fedlimit,rail,road,popplace",
transparent: "true",
format: "image/png"
},
{ isBaseLayer: false }
);
I get this view on browser:
Any idea why I get the error above when I try to overlay a layer?
The server "http://www2.dmsolutions.ca/cgi-bin/mswms_gmap" seems to be down , try with another WMS like
http://129.206.228.72/cached/osm
var dm_wms = new OpenLayers.Layer.WMS(
"OSM example",
"http://129.206.228.72/cached/osm?",
{
layers: "osm_auto:all"
transparent: "true",
format: "image/png"
},
{ isBaseLayer: false }
);
Related
I'm working with the ArcGIS API for JavaScript. I wondering is there any features I can use to get the coordinates of each vertex after I draw using the Sketch tool in the ArcGiS API?
Update
I try to use the webmercator method but it keep appear this error to me
"webMercatorUtils.webMercatorToGeographic is not a function"
this is the code i written to parse it.
sketch.on("create", (e: __esri.SketchCreateEvent) => {
if (e.state === "complete") {
// this.rings = e.graphic.geometry.toJSON().rings.webMercatorUtils.webMercatorToGeographic();
this.rings = webMercatorUtils.webMercatorToGeographic(e.graphic.geometry);
}
});
Error
Sketch widget has a series of events that you can bind to get the information you are looking for.
In your case, use create event.
ArcGIS API - Sketch
Take a look at this simple example I put for you.
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no">
<title>Sketch</title>
<style>
html, body, #viewDiv {
padding: 0;
margin: 0;
height: 100%;
width: 100%;
}
</style>
<link rel="stylesheet" href="https://js.arcgis.com/4.21/esri/css/main.css">
<script src="https://js.arcgis.com/4.21/"></script>
<script>
require([
"esri/widgets/Sketch",
"esri/Map",
"esri/layers/GraphicsLayer",
"esri/views/MapView"
], (Sketch, Map, GraphicsLayer, MapView) => {
const graphicsLayer = new GraphicsLayer();
const map = new Map({
basemap: "topo-vector",
layers: [graphicsLayer]
});
const view = new MapView({
container: "viewDiv",
map: map,
zoom: 5,
center: [90, 45]
});
view.when(() => {
const sketch = new Sketch({
layer: graphicsLayer,
view: view
});
sketch.on("create", function(event) {
if (event.state === "complete") {
console.log(event.graphic.geometry.toJSON());
}
});
view.ui.add(sketch, "top-right");
});
});
</script>
</head>
<body>
<div id="viewDiv"></div>
</body>
</html>
UPDATE
Here is the same code with the addition to convert the geometry from WebMercator (wkid 102100 or 3857) to geographics (wkid 4326)
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no">
<title>Sketch</title>
<style>
html, body, #viewDiv {
padding: 0;
margin: 0;
height: 100%;
width: 100%;
}
</style>
<link rel="stylesheet" href="https://js.arcgis.com/4.21/esri/css/main.css">
<script src="https://js.arcgis.com/4.21/"></script>
<script>
require([
"esri/widgets/Sketch",
"esri/Map",
"esri/layers/GraphicsLayer",
"esri/views/MapView",
"esri/geometry/support/webMercatorUtils"
], (Sketch, Map, GraphicsLayer, MapView, webMercatorUtils) => {
const graphicsLayer = new GraphicsLayer();
const map = new Map({
basemap: "topo-vector",
layers: [graphicsLayer]
});
const view = new MapView({
container: "viewDiv",
map: map,
zoom: 5,
center: [90, 45]
});
view.when(() => {
const sketch = new Sketch({
layer: graphicsLayer,
view: view
});
sketch.on("create", function(event) {
if (event.state === "complete") {
console.log(event.graphic.geometry.toJSON());
console.log(webMercatorUtils.webMercatorToGeographic(event.graphic.geometry).toJSON());
}
});
view.ui.add(sketch, "top-right");
});
});
</script>
</head>
<body>
<div id="viewDiv"></div>
</body>
</html>
I have built an Android app using Cordova following these instructions
https://cordova.apache.org/docs/en/latest/guide/cli/index.html
All works well except the map shows when I run emulate browser or emulate android, but not when I install the apk to my J5 Samsung phone.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="format-detection" content="telephone=no" />
<meta name="msapplication-tap-highlight" content="no" />
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width" />
<meta http-equiv="Content-Security-Policy" content="default-src *; script-src 'self' 'unsafe-inline' 'unsafe-eval' *; style-src 'self' 'unsafe-inline' *; img-src * data: 'unsafe-inline'">
<!-- This is a wide open CSP declaration. To lock this down for production, see below. -->
<meta http-equiv="Content-Security-Policy" content="default-src * 'unsafe-inline' gap:; style-src 'self' 'unsafe-inline'; media-src *" />
<!-- Good default declaration:
* gap: is required only on iOS (when using UIWebView) and is needed for JS->native communication
* https://ssl.gstatic.com is required only on Android and is needed for TalkBack to function properly
* Disables use of eval() and inline scripts in order to mitigate risk of XSS vulnerabilities. To change this:
* Enable inline JS: add 'unsafe-inline' to default-src
* Enable eval(): add 'unsafe-eval' to default-src
* Create your own at http://cspisawesome.com
-->
<!-- <meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: 'unsafe-inline' https://ssl.gstatic.com; style-src 'self' 'unsafe-inline'; media-src *" /> -->
<link rel="stylesheet" type="text/css" href="css/index.css" />
<title>Hello World</title>
</head>
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map { height: 100% }
</style>
<body>
<div class="app">
<h1>PhoneGap</h1>
<div id="deviceready" class="blink">
<p class="event listening">Connecting to Device</p>
<p class="event received">Device is Ready</p>
</div>
</div>
<div id="geolocation"></div>
<button type="button" onclick="addMarker()">Add Marker</button>
<div id="map">MAP HERE</div>
<script src="/__/firebase/4.13.0/firebase-app.js"></script>
<script src="/__/firebase/4.13.0/firebase-auth.js"></script>
<script src="/__/firebase/4.13.0/firebase-database.js"></script>
<script src="/__/firebase/4.13.0/firebase-messaging.js"></script>
<script src="/__/firebase/4.13.0/firebase-functions.js"></script>
<!-- Leave out Storage -->
<!-- <script src="/__/firebase/4.13.0/firebase-storage.js"></script> -->
<script src="/__/firebase/init.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyA8RwcNCgxRCRpiSgiRpr_InT2Vt-aDwPQ" type="text/javascript"></script>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<script type="text/javascript">
app.initialize();
</script>
</body>
</html>
<script src="https://www.gstatic.com/firebasejs/4.13.0/firebase.js"></script>
<script>
// Initialize Firebase
var config = {
.............
};
firebase.initializeApp(config);
</script>
And js file
var test=5;
var json = [
{
lat: 55.5,
lng: -4
},
{
lat:56,
lng: -4.5
}
];
var Latitude = undefined;
var Longitude = undefined;
// Get geo coordinates
function getMapLocation() {
navigator.geolocation.getCurrentPosition
(onMapSuccess, onMapError, { enableHighAccuracy: true });
}
// Success callback for get geo coordinates
var onMapSuccess = function (position) {
Latitude = position.coords.latitude;
Longitude = position.coords.longitude;
getMap(Latitude, Longitude);
};
// Get map by using coordinates
function getMap(latitude, longitude) {
var mapOptions = {
center: new google.maps.LatLng(0, 0),
zoom: 1,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map
(document.getElementById("map"), mapOptions);
var latLong = new google.maps.LatLng(latitude, longitude);
var marker = new google.maps.Marker({
position: latLong
});
//marker.setMap(map);
map.setZoom(9);
map.setCenter(marker.getPosition());
showMarkers();
}
// Success callback for watching your changing position
var onMapWatchSuccess = function (position) {
var updatedLatitude = position.coords.latitude;
var updatedLongitude = position.coords.longitude;
if (updatedLatitude != Latitude && updatedLongitude != Longitude) {
Latitude = updatedLatitude;
Longitude = updatedLongitude;
getMap(updatedLatitude, updatedLongitude);
}
};
// Error callback
function onMapError(error) {
console.log('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
// Watch your changing position
function watchMapPosition() {
return navigator.geolocation.watchPosition
(onMapWatchSuccess, onMapError, { timeout: 30000 });
}
function showMarkers(){
for(var i=0;i<json.length;i++) {
data = json[i];
var latLong = new google.maps.LatLng(data.lat, data.lng);
var marker = new google.maps.Marker({
position: latLong
});
marker.setMap(map);
}
}
function addMarker(){
var newMarker = new Object();
newMarker["lat"] = Latitude;
newMarker["lng"] = Longitude;
writeCoords("abc",Latitude, Longitude);
json.push(newMarker);
showMarkers();
}
function readMarkers(){
var activeRef = firebase.database().ref('location/');
activeRef.on('value', function(snapshot){
snapshot.forEach(function(childSnapshot) {
alert(childSnapshot.val().latitude);
});
});
}
watchMapPosition();
function writeCoords(userId, lat, lng){
firebase.database().ref('location/' + firebase.database().ref().child('location').push().key).set({
latitude: lat,
longitude: lng
});
}
var app = {
// Application Constructor
initialize: function() {
document.addEventListener('deviceready', this.onDeviceReady.bind(this), false);
},
// deviceready Event Handler
//
// Bind any cordova events here. Common events are:
// 'pause', 'resume', etc.
onDeviceReady: function() {
this.receivedEvent('deviceready');
},
// Update DOM on a Received Event
receivedEvent: function(id) {
var parentElement = document.getElementById(id);
var listeningElement = parentElement.querySelector('.listening');
var receivedElement = parentElement.querySelector('.received');
listeningElement.setAttribute('style', 'display:none;');
receivedElement.setAttribute('style', 'display:block;');
console.log('Received Event: ' + id);
}
};
app.initialize();
And the config.xml as this can be where problems lie
<?xml version='1.0' encoding='utf-8'?>
<widget id="com.example.hello" version="1.0.0" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">
<name>HelloWorld</name>
<description>
A sample Apache Cordova application that responds to the deviceready event.
</description>
<author email="dev#cordova.apache.org" href="http://cordova.io">
Apache Cordova Team
</author>
<content src="index.html" />
<plugin name="cordova-plugin-whitelist" spec="1" />
<access origin="*" />
<allow-intent href="http://*/*" />
<allow-intent href="https://*/*" />
<allow-intent href="tel:*" />
<allow-intent href="sms:*" />
<allow-intent href="mailto:*" />
<allow-intent href="geo:*" />
<platform name="android">
<allow-intent href="market:*" />
</platform>
<platform name="ios">
<allow-intent href="itms:*" />
<allow-intent href="itms-apps:*" />
</platform>
<engine name="android" spec="~6.1.2" />
</widget>
All works fine on emulators and I can upload to Firebase using the marker button. When it moves to the phone itself, I see everything but the map.
Well I did 2 things. Installed cordova plugin add cordova-plugin-geolocation and unplugged the usb from phone after installation. Not sure if both were required, but it works now.
I have a simple openlayer programm to add circle on mouse click. But for new circle it will remove last ones.I am giving jsfiddel link. kindly update it if you can help. further code is also here .
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta name="robots" content="noindex, nofollow">
<meta name="googlebot" content="noindex, nofollow">
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<link rel="stylesheet" type="text/css" href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css">
<script type="text/javascript" src="http://openlayers.org/api/OpenLayers.js"></script>
<link rel="stylesheet" type="text/css" href="http://openlayers.org/en/v3.16.0/css/ol.css">
<style type="text/css">
</style>
<script type='text/javascript'>
//<![CDATA[
$(window).load(function() {
function updateIcon(f) {
vector.drawFeature(f);
}
options = {
div: "map",
zoom: 2,
center: [0, 0],
layers: [
new OpenLayers.Layer.OSM()
]
};
map = new OpenLayers.Map(options);
vector = new OpenLayers.Layer.Vector();
map.addLayer(vector);
var point1 = new OpenLayers.Geometry.Point(0, 0);
var point2 = new OpenLayers.Geometry.Point(5000000, 1000000);
var point3 = new OpenLayers.Geometry.Point(2000000, 2000000);
var radius = $("#amount").val();
var mycircle = OpenLayers.Geometry.Polygon.createRegularPolygon(point2, radius, 20, 0);
var featurecircle = new OpenLayers.Feature.Vector(mycircle);
///vector.addFeatures([featurecircle]);
OpenLayers.Control.Click = OpenLayers.Class(OpenLayers.Control, {
defaultHandlerOptions: {
'single': true,
'double': false,
'pixelTolerance': 0,
'stopSingle': false,
'stopDouble': false
},
initialize: function(options) {
this.handlerOptions = OpenLayers.Util.extend({}, this.defaultHandlerOptions);
OpenLayers.Control.prototype.initialize.apply(
this, arguments
);
this.handler = new OpenLayers.Handler.Click(
this, {
'click': this.trigger
}, this.handlerOptions
);
},
trigger: function(e) {
console.log(map)
console.log(e)
var lonlat = map.getLonLatFromPixel(e.xy);
var newPoint = new OpenLayers.Geometry.Point(lonlat.lon, lonlat.lat);
vector.removeFeatures([featurecircle]);
var mycircle = OpenLayers.Geometry.Polygon.createRegularPolygon(
newPoint,
radius,
40,
0
);
featurecircle = new OpenLayers.Feature.Vector(mycircle);
vector.addFeatures([featurecircle]);
}
});
var click = new OpenLayers.Control.Click();
map.addControl(click);
click.activate();
}); //]]>
</script>
</head>
<body>
<p>
<input type="text" id="amount" value="1000000" style="border:0; color:#f6931f; font-weight:bold;">
</p>
<div id="slider-range-max"></div>
<div id="map" style="width:600px;height:600px;"></div>
</body>
</html>
http://jsfiddle.net/zLjae81b/30/
Why don't you want to remove while removing it yourself?
Just remove the removing code (line 108):
vector.removeFeatures([featurecircle]);
The following code adds four markers to the map. Number of markers may be more than four. How can I play a beep sound after displaying each and every marker in the map? And, is it possible to increase or decrease the volume of the beep depending upon some value ?
<!DOCTYPE html>
<html>
<head>
<title>Simple Leaflet Map</title>
<meta charset="utf-8" />
<link
rel="stylesheet"
href="http://cdn.leafletjs.com/leaflet-0.7/leaflet.css"
/>
</head>
<body>
<div id="map" style="width: 600px; height: 400px"></div>
<script
src="http://cdn.leafletjs.com/leaflet-0.7/leaflet.js">
</script>
<script>
var planes = [
["Marker1",-40.99497,174.50808],
["Marker2",-41.30269,173.63696],
["Marker3",-41.49413,173.5421],
["Marker4",-41.51285,173.63274]
];
var map = L.map('map').setView([-41.3058, 174.82082], 8);
mapLink =
'OpenStreetMap';
L.tileLayer(
'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© ' + mapLink + ' Contributors',
maxZoom: 18,
}).addTo(map);
var myIcon = L.icon({
iconUrl: 'http://leafletjs.com/dist/images/marker-icon.png',
iconSize: [25, 25]
});
function beep() {
var snd = new
snd.play();
}
for (var i = 0; i < planes.length; i++) {
marker = new L.marker([planes[i][1],planes[i][2]], {icon: myIcon})
.bindPopup(planes[i][0])
.addTo(map);
.beep();
}
</script>
</body>
</html>
After suggestions from colleagues, I tried this way and it works. Thanks to all.
<!DOCTYPE html>
<html>
<head>
<title>Simple Leaflet Map</title>
<meta charset="utf-8" />
<link
rel="stylesheet"
href="http://cdn.leafletjs.com/leaflet-0.7/leaflet.css"
/>
</head>
<body>
<div id="map" style="width: 600px; height: 400px"></div>
<script
src="http://cdn.leafletjs.com/leaflet-0.7/leaflet.js">
</script>
<script>
var planes = [
["Marker1",-40.99497,174.50808],
["Marker2",-41.30269,173.63696],
["Marker3",-41.49413,173.5421],
["Marker4",-41.51285,173.63274]
];
var map = L.map('map').setView([-41.3058, 174.82082], 8);
mapLink =
'OpenStreetMap';
L.tileLayer(
'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: '© ' + mapLink + ' Contributors',
maxZoom: 18,
}).addTo(map);
var myIcon = L.icon({
iconUrl: 'http://leafletjs.com/dist/images/marker-icon.png',
iconSize: [25, 25]
});
</script>
<audio id="audio" src="D:\check\beep.mp3" autostart="false" ></audio>
<script>
function PlaySound() {
var sound = document.getElementById("audio");
sound.play()
}
</script>
<script>
for (var i = 0; i < planes.length; i++) {
marker = new L.marker([planes[i][1],planes[i][2]], {icon: myIcon})
.bindPopup(planes[i][0])
.addTo(map);
PlaySound();
}
</script>
</body>
</html>
I have this html file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
<meta name="description" content="" />
<meta name="author" content="Salvatore Mazzarino" />
<meta name="viewport" content="width=device-width; initial-scale=1.0" />
<!-- jquery mobile scripts -->
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.0.1/jquery.mobile- 1.0.1.min.css" />
<script src="http://code.jquery.com/jquery-1.6.4.min.js"></script>
<script src="http://code.jquery.com/mobile/1.0.1/jquery.mobile-1.0.1.min.js"></script>
<!-- my own style sheet -->
<link rel="stylesheet" href="./assets/css/style.css" type="text/css" />
<!-- google maps api script -->
<script type="text/javascript" src="./includes/js_map.js"></script>
<script src="http://maps.google.com/maps/api/jssensor=false"></script>
</head>
<body>
<div data-role = "page" id = "map-page">
<div data-role = "header">
<h1>Your position</h1>
</div>
<div data-role = "content" id = "map-canvas">
<!-- here the map -->
</div>
</div>
</body>
</html>
and this js file :
$( "#map-page" ).live( "pageinit", function()
{
// Default to Via Messina,Catania,IT when no geolocation support
var defaultLatLng = new google.maps.LatLng(37.530073, 15.112151);
if ( navigator.geolocation )
{
function success(pos)
{
// Location found, show coordinates on map
drawMap(new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude));
}
function fail()
{
drawMap(defaultLatLng); // Show default map
}
// Find users current position
navigator.geolocation.getCurrentPosition(success, fail, {enableHighAccuracy:true, timeout: 6000, maximumAge: 500000});
}
else
{
drawMap(defaultLatLng); // No geolocation support
}
function drawMap(latlng) {
var myOptions = {
zoom: 10,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(
document.getElementById("map-canvas"), myOptions);
// Add an overlay to the map of current lat/lng
var marker = new google.maps.Marker({
position: latlng,
map: map,
title: "Greetings!"
});
}
});
I'm trying to obtain my position.in the html page a mas should appears but nothing apper neither the default map. why? any idea?
Without seeing your live code, it's hard to see if any of the CSS might be causing display issues. However, there are at least two things that need to be fixed:
Your call to the Google Maps API needs to be moved above your own JS file (in the head of the document).
You have an error in your URL that references the Maps API JS file. Change it from:
http://maps.google.com/maps/api/jssensor=false
to:
http://maps.google.com/maps/api/js?sensor=false
I was able to get the map to load and show a marker in the middle of the map.