I have done the below code to create a layer and then found the coordinates which shows in the side div.
But when i click on the button i need to check whether the point(6,79) lies inside the polygon or on the edge of it.
I have used(mapbox/leaflet) to do all these.
So please do help me to get this done.
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Show drawn polygon area</title>
<meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />
<script src='https://api.tiles.mapbox.com/mapbox.js/v2.1.4/mapbox.js'></script>
<link href='https://api.tiles.mapbox.com/mapbox.js/v2.1.4/mapbox.css' rel='stylesheet' />
<style>
body { margin:0; padding:0; }
#map { position:absolute; top:0; bottom:0; width:75%; height: 75%; border: 1px solid black;}
#details { width:200px ; height: 200px; border: 1px solid black; float:right;}
#details2 { width:80px ; height: 200px; border: 1px solid black; float:right}
</style>
</head>
<body onload="load();">
<link href='https://api.tiles.mapbox.com/mapbox.js/plugins/leaflet-draw/v0.2.2/leaflet.draw.css' rel='stylesheet' />
<script src='https://api.tiles.mapbox.com/mapbox.js/plugins/leaflet-draw/v0.2.2/leaflet.draw.js'></script>
<script src='https://api.tiles.mapbox.com/mapbox.js/plugins/leaflet-geodesy/v0.1.0/leaflet-geodesy.js'></script>
<script src='https://code.jquery.com/jquery-1.11.0.min.js'></script>
<script src='https://api.tiles.mapbox.com/mapbox.js/plugins/leaflet-pip/v0.0.2/leaflet-pip.js'></script>
<div id='map'></div>
<script>
L.mapbox.accessToken = 'pk.eyJ1IjoiYXNoYW4iLCJhIjoiQzQySHN1QSJ9.K4xoMZqrVsWBgYTp70CYNg';
var map = L.mapbox.map('map', 'examples.map-i86l3621')//examples.map-i86nkdio')
.setView([6.9344,79.8428], 10);
var featureGroup = L.featureGroup().addTo(map);
var drawControl = new L.Control.Draw({
edit: {
featureGroup: featureGroup
},
draw: {
polygon: true,
polyline: true,
rectangle: true,
circle: true,
marker: true
}
}).addTo(map);
map.on('draw:created', showPolygonArea);
map.on('draw:edited', showPolygonAreaEdited);
function showPolygonAreaEdited(e) {
e.layers.eachLayer(function(layer) {
showPolygonArea({ layer: layer });
});
}
function showPolygonArea(e) {
featureGroup.clearLayers();
featureGroup.addLayer(e.layer);
e.layer.bindPopup((LGeo.area(e.layer) / 1000000).toFixed(2) + ' km<sup>2</sup>');
e.layer.openPopup();
}
var drawnItems = new L.featureGroup();
map.addLayer(drawnItems);
map.on('draw:created', function (e) {
var type = e.layerType,
layer = e.layer;
drawnItems.addLayer(layer);
var shapes = getShapes(drawnItems);
document.getElementById('details').innerHTML = shapes ;
});
var getShapes = function(drawnItems) {
var shapes = [];
drawnItems.eachLayer(function(layer) {
if (layer instanceof L.Polyline) {
shapes.push(layer.getLatLngs())
}
if (layer instanceof L.Circle) {
shapes.push([layer.getLatLng()])
}
if (layer instanceof L.Marker) {
shapes.push([layer.getLatLng()]);
}
});
return shapes;
};
function checkfunction(e) {
shapes = getShapes(drawnItems);
var bounds= drawnItems.getBounds();
for (var i = 0; i < latlong.length; i++){
var hello =new google.maps.LatLng(6.9344, 79.8428);
if(bounds.contains(hello)) {
alert("Red");
} else {
alert("Green");
}
}
}
</script>
<div id="details" >
</div>
<div id="details2" >
<input type="button" value="Check" id="check" onclick="checkfunction();" />
</div>
</body>
</html>
Thanks,
Ashan.
I had a bit of a hard time understanding your code - for example, why does it use new google.maps.LatLng if you're using Leaflet?
Anyway, it sounds like you want to use a library for performing point in polygon tests. There's a library called leaflet-pip from Mapbox, that will most likely do what you need. You can find an example here: https://www.mapbox.com/mapbox.js/example/v1.0.0/point-in-polygon/
Related
I'm trying to build a small project where we get specific nearby places (schools, hospitals, cafes etc) around 5kms radius on clicking a radio button.Here I'm trying to use the geolocation to get the dynamic location(latitude and longitude) so that I can get user current location where ever this app is used.What happening is, the map is not loading on page load while the first radio button is already checked but it is working fine when I switch to other radio buttons.
I'm not an expert in JavaScript.
Below is my HTML code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Google Maps</title>
<style>
#map {
height: 100%;
width: 100%;
}
#box{
height:500px;
width:80%;
margin-left:10%;
margin-right:10%;
border:2px solid black;
}
h1{
text-align:center;
font-family:sans-serif;
}
form {
text-align: center;
}
</style>
</head>
<body>
<h1>Google Maps</h1>
<form>
<input type="radio" id="school" name="places" value="School" checked onClick="load();">Schools
<input type="radio" id="hospital" name="places" value="Hospital" onClick="load();">Hospitals
<input type="radio" id="cafe" name="places" value="Hotel" onClick="load();">Cafes
<input type="radio" id="atm" name="places" value="atm" onClick="load();">ATM's
</form>
<br>
<div id="box">
<div id="map"></div>
</div>
<script type = "text/javascript" src="maps.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBVOCb1nOuIrbnvnTYIYTKMqs2y5ecuMi8&signed_in=true&libraries=places&callback=load" async defer></script>
</body>
</html>
Here's my JavaScript code
var map;
var infowindow;
var myLat;
var myLong;
x = navigator.geolocation;
x. getCurrentPosition(success);
function success(position){
myLat = position.coords.latitude;
myLong = position.coords.longitude;
}
function load() {
//var hyderabad = {lat: 17.46724, lng: 78.53591};
var hyderabad = new google.maps.LatLng(myLat , myLong);
map = new google.maps.Map(document.getElementById('map'), {
center: hyderabad,
zoom: 12
});
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
var place;
if (document.getElementById('school').checked) {
place = "school"
}
else if (document.getElementById('hospital').checked) {
place = "hospital"
}
else if (document.getElementById('cafe').checked) {
place = "cafe"
}
else if (document.getElementById('atm').checked) {
place = "atm"
}
service.nearbySearch({
location: hyderabad,
radius: 5000,
type: [place]
}, callback);
}
function callback(results, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
}
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
google.maps.event.addListener(marker, 'mouseover', function() {
infowindow.setContent(place.name);
infowindow.open(map, this);
});
}
Any GeoJSON, just always puts Points on the bottom left side of Africa, even, though, there are coordinates section in GeoJSON.
I use openlayers v3.20.1
GeoJSON, I've tried to use is from:
https://raw.githubusercontent.com/acanimal/Openlayers-Cookbook/master/recipes/data/world_cities.json
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>The Book of OpenLayers3 - Code samples</title>
<link rel="stylesheet" href="progr/nm/ol.css" type="text/css">
<script src="progr/nm/jquery-3.1.1.min.js" type="text/javascript"></script>
<script src="progr/nm/ol.js" type="text/javascript"></script>
<style type="text/css">
.map {
width: calc(50% - 6px - 1em);
height: 500px;
box-shadow: 4px 4px 20px black;
border: 3px solid blue;
float: left;
}
#edit {
padding: 1em;
height: calc(500px - 2em);
}
textarea {
width: 100%;
height: calc(100% - 4em);
}
.tree {
width: auto;
border: 3px solid red;
background: yellow;
float: left;
}
</style>
</head>
<body>
<dev id='map' class='map col-sm-6'></dev>
<dev id='edit' class='map col-sm-6'>
<textarea id='read'></textarea>
<p class='text-primary'>
Paste any valid GeoJSON string and press the <button id='readButton' class='btn btn-primary btn-xs'>Read button</button>.
</p>
</dev>
<script>
var format = new ol.format.GeoJSON();
var layers = {
OSM: new ol.layer.Tile({source: new ol.source.OSM()}),
vec: new ol.layer.Vector({
source: new ol.source.Vector({
format: format,
projection: 'EPSG:3857'
})
})
};
var maps = {
map: new ol.Map({
target: 'map',
renderer: 'canvas',
layers: [layers['OSM'], layers['vec']],
view: new ol.View({
center: ol.proj.transform([0, 0], 'EPSG:4326', 'EPSG:3857'),
zoom: 2
})
})
};
$('#readButton').on('click', function(){
var src = layers['vec'].getSource();
var txt = $('#read').val();
if(txt === ''){
src.clear();
return;
}
var json = JSON.parse(txt);
var feat = format.readFeatures(json);
src.addFeatures(feat);
});
</script>
</body>
</html>
I've also tried to pass 'txt' content directly to readFeatures method, but it made no difference.
var feat = format.readFeatures(txt);
src.addFeatures(feat);
There is no issue with the geoJSON or its parsing. The error is a projection/coordinate system issue. The map projection you are using does not use lat longs as its unit of measurement. Instead the unit of measurement for the default projection you are using, web Mercator (EPSG:3857), is meters. Whereas the json file you are using uses WGS84, or lat long pairs.
Therefore, all your points are clustered +/- 180 east/west and +/- 90 meters north/south of the intersection of the Prime Meridian and the Equator [0,0], which is off the East coast of Africa. If you zoom in very very far, copying and pasting the json file you linked to, you will find:
You can fix this by ensuring your data is reprojected for display. The only changes I made were in the on click event:
$('#readButton').on('click', function(){
var src = layers['vec'].getSource();
var txt = $('#read').val();
if(txt === ''){
src.clear();
return;
}
var json = JSON.parse(txt);
var feat = format.readFeatures(json, {
dataProjection: 'EPSG:4326', // define the input SRS/CRS
featureProjection: 'EPSG:3857' // define the output SRS/CRS
});
src.addFeatures(feat);
});
By subbing in this for you onclick event I got:
I'm starting with jQueryMobile and wanted to display a map using OpenLayers. However I'm having a weird issue. Here is the almost working code. Sorry I couldn't make a fiddle, however you can test it easily with copy/paste on notepad or whatever.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<script src="http://www.openlayers.org/api/OpenLayers.js"></script>
<style type="text/css">
html ,body {
margin: 0;
padding: 0;
height: 100%;
}
.ui-content {
padding: 0;
}
#pageone, #pageone .ui-content, #basicMap {
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<div data-role="page" id="pageone">
<div data-role="main" class="ui-content">
<div id="basicMap"></div>
</div>
</div>
<script>
function init() {
map = new OpenLayers.Map("basicMap", {
controls: [
new OpenLayers.Control.Navigation(),
new OpenLayers.Control.ArgParser(),
new OpenLayers.Control.Attribution()
]
});
var mapnik = new OpenLayers.Layer.OSM();
var fromProjection = new OpenLayers.Projection("EPSG:4326"); // Transform from WGS 1984
var toProjection = new OpenLayers.Projection("EPSG:900913"); // to Spherical Mercator Projection
var position = new OpenLayers.LonLat(7.55785346031189,50.3625329673905).transform( fromProjection, toProjection);
var zoom = 3;
map.addLayer(mapnik);
map.setCenter(position, zoom );
var markers = new OpenLayers.Layer.Markers( "Markers" );
map.addLayer(markers);
var marker = new OpenLayers.Marker(position);
marker.events.register("click", map , function(e){ alert("click");
});
markers.addMarker(marker);
}
$(document).on("pagecreate","#pageone",init());
</script>
</body>
</html>
This code doesn't show the map.
Now if you take off the following line :
<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
You can see that the map is showing.
Any idea on how can I solve this ? because I think it can be solved easily but can't see how.
Thank you.
I knew it was stupid, if it can interest someone , the css should be like :
#pageone, #pageone .ui-content, #basicMap {
width: 100%;
height: 100%;
display : block;
}
And call JS :
$(document).ready(init());
Don't know however why this works.
I have added layers into the page and trying to get layer feature attributes on button click using ARCGIS Javascript API. The mapView is loading corretly with Legends and all details in it. But the tool for fetching layer attributes on button click not working. Here is my code
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<!--The viewport meta tag is used to improve the presentation and behavior of the samples
on iOS devices-->
<meta name="viewport" content="initial-scale=1, maximum-scale=1,user-scalable=no">
<title>Map with legend</title>
<link rel="stylesheet" href="http://js.arcgis.com/3.10/js/esri/css/esri.css">
<style>
html, body {
height:100%;
width:100%;
margin:0;
padding:0;
}
#search{
display: block;
position: absolute;
z-index: 2;
top: 20px;
left: 74px;
}
#execute{
display: block;
position: absolute;
z-index: 2;
top: 20px;
left: 74px;
}
#rightPane {
width: 20%;
}
#legendPane {
border: solid #97DCF2 1px;
}
</style>
<script src="http://js.arcgis.com/3.10/"></script>
<script>
var map;
require([
"esri/map","esri/layers/FeatureLayer","esri/dijit/Legend",
"dojo/_base/array","dojo/parser",
"dijit/layout/BorderContainer","dijit/layout/ContentPane",
"dijit/layout/AccordionContainer","esri/tasks/query",
"esri/tasks/QueryTask","dojo/dom","dojo/on","dojo/domReady!"
], function(
Map, FeatureLayer, Legend,
arrayUtils, parser,
Query,QueryTask,dom,on
) {
parser.parse();
map = new Map("map", {
basemap:"topo",
center: [78.629, 18.092],
zoom: 5
});
var offices = new FeatureLayer("http://localhost:6080/arcgis/rest/services/FrimData/MapServer/0", {
mode: FeatureLayer.MODE_ONDEMAND,
outFields:["*"]
});
var route = new FeatureLayer("http://localhost:6080/arcgis/rest/services/FrimData/MapServer/1", {
mode: FeatureLayer.MODE_ONDEMAND,
outFields:["*"]
});
var depth = new FeatureLayer("http://localhost:6080/arcgis/rest/services/FrimData/MapServer/2", {
mode: FeatureLayer.MODE_ONDEMAND,
outFields:["*"]
});
var economicZone = new FeatureLayer("http://localhost:6080/arcgis/rest/services/FrimData/MapServer/3", {
mode: FeatureLayer.MODE_ONDEMAND,
outFields:["*"]
});
var boundary = new FeatureLayer("http://localhost:6080/arcgis/rest/services/FrimData/MapServer/4", {
mode: FeatureLayer.MODE_ONDEMAND,
outFields:["*"]
});
//add the legend
map.on("layers-add-result", function (evt) {
var layerInfo = arrayUtils.map(evt.layers, function (layer, index) {
return {layer:layer.layer, title:layer.layer.name};
});
if (layerInfo.length > 0) {
var legendDijit = new Legend({
map: map,
layerInfos: layerInfo
}, "legendDiv");
legendDijit.startup();
}
});
map.addLayers([route,depth,economicZone,boundary,offices]);
var queryTask = new QueryTask("http://localhost:6080/arcgis/rest/services/FrimData/MapServer/0");
var query = new Query();
query.returnGeometry = false;
query.outFields = [
"Name", "OBJECTID"
];
on(dom.byId("execute"), "click", executes);
function executes () {
alert("df");
query.text = dom.byId("stateName").value;
queryTask.execute(query, showResults);
}
function showResults(results){
var resultItems = [];
var resultCount = results.features.length;
for (var i = 0; i < resultCount; i++) {
var featureAttributes = results.features[i].attributes;
for (var attr in featureAttributes) {
alert(featureAttributes[attr]);
resultItems.push("<b>" + attr + ":</b> " + featureAttributes[attr] + "<br>");
}
resultItems.push("<br>");
}
}
});
</script>
</head>
<body class="claro">
<!--[if IE 7]>
<style>
html, body {
margin: 0;
}
</style>
<![endif]-->
<div id="content"
data-dojo-type="dijit/layout/BorderContainer"
data-dojo-props="design:'headline', gutters:true"
style="width: 100%; height: 100%; margin: 0;">
<div id="rightPane"
data-dojo-type="dijit/layout/ContentPane"
data-dojo-props="region:'right'">
<div data-dojo-type="dijit/layout/AccordionContainer">
<div data-dojo-type="dijit/layout/ContentPane" id="legendPane"
data-dojo-props="title:'Legend', selected:true">
<div id="legendDiv"></div>
</div>
<div data-dojo-type="dijit/layout/ContentPane"
data-dojo-props="title:'Pane 2'">
This pane could contain tools or additional content
</div>
</div>
</div>
<div id="map"
data-dojo-type="dijit/layout/ContentPane"
data-dojo-props="region:'center'"
style="overflow:hidden;">
</div>
<div id="search"></div>
<input type="text" id="stateName" value="1">
<input id="execute" type="button" value="Get Details">
</div>
</body>
</html>
From the step button click on(dom.byId("execute"), "click", executes); It is not working. I refered this example https://developers.arcgis.com/javascript/jssamples/query_nomap.htmlI am new to this. Please help me guys.
you have a mismatch in the AMD modules you require and modules you actually reference for the function. Hope that helps
var map;
require([
"esri/map",
"esri/layers/FeatureLayer",
"esri/dijit/Legend",
"dojo/_base/array",
"dojo/parser",
"dijit/layout/BorderContainer",
"dijit/layout/ContentPane",
"dijit/layout/AccordionContainer",
"esri/tasks/query",
"esri/tasks/QueryTask",
"dojo/dom",
"dojo/on","dojo/domReady!"
], function(
Map, FeatureLayer, Legend, arrayUtils, parser, BorderContainer, ContentPane, AccordionContainer, Query, QueryTask, dom, on
) {
parser.parse();
map = new Map("map", {
basemap:"topo",
center: [78.629, 18.092],
zoom: 5
});
on(dom.byId("execute"), "click", function() {
console.info("got it");
alert("df");
});
});
This works well enough but I was wondering how I could suspend the script after a user hovers their mouse over it. Is there some command within the API that would help me do this? What about just some kind of function suspension?
<DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Street View service</title>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script>
var panorama;
function initialize() {
var fenway = new google.maps.LatLng(42.345573,-71.098326);
var panoramaOptions = {
position: fenway,
pov: {
heading: 4,
pitch: 10
}
};
panorama = new google.maps.StreetViewPanorama(document.getElementById('pano'),panoramaOptions);
var i = 0;
window.setInterval(function () {
panorama.setPov({
heading: i,
pitch: 10,
zoom: 1
});
i += 0.1;
}, 10);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas" style="width: 400px; height: 300px"></div>
<div id="pano" style="position:absolute; left:410px; top: 8px; width: 400px; height: 300px;"></div>
</body>
</html>
You can use this great tool to generate an embed code for your site: http://virali.se/photo/spin/
It also uses Google API.
Editing your code you can add the following:
$("#pano").on("mouseenter", function () {
move = false;
});
$("#pano").on("mouseleave", function () {
move = true;
});
...
if (move) { i += 0.1; }
Demo in this JSFIDDLE.