Hi everyone i develop web map using openlayer.
i use geojson, i have this code from :
https://scraperwiki.com/views/openlayers_geojson_example/edit/
this is code :
<script type="text/javascript">
// Start position for the map (hardcoded here for simplicity)
var lat=50.90685
var lon=-1.4029
var zoom=12
var map; //complex object of type OpenLayers.Map
//Initialise the 'map' object
$(function() {
$.getJSON("http://mapit.mysociety.org/area/66016.geojson",
"callback=?",
function(data, textStatus, jqXHR) {
map = new OpenLayers.Map('map', {
layers: [
new OpenLayers.Layer.OSM.Mapnik("Mapnik"),
],
controls: [
new OpenLayers.Control.Navigation(),
new OpenLayers.Control.PanZoomBar(),
new OpenLayers.Control.LayerSwitcher(),
new OpenLayers.Control.Attribution()],
maxResolution: 'auto',
});
var lonLat = new OpenLayers.LonLat(lon, lat)
.transform(
new OpenLayers.Projection("EPSG:4326"),
map.getProjectionObject()
);
map.setCenter(lonLat, zoom);
var vector_layer = new OpenLayers.Layer.Vector("GeoJSON");
var geojson_format = new OpenLayers.Format.GeoJSON();
var geometry = geojson_format.parseGeometry(data);
geometry.transform(
new OpenLayers.Projection("EPSG:4326"),
map.getProjectionObject()
);
var feature = new OpenLayers.Feature.Vector(geometry);
vector_layer.addFeatures([feature]);
map.addLayer(vector_layer);
})
});
</script>
in :
$.getJSON("http://mapit.mysociety.org/area/66016.geojson",
"callback=?",
it works when i call from iis localhost
i try to change like this :
$.getJSON("assets/json/66016.geojson",
"callback=?",
but it didnt work, :(
please help me why and how to make this work.
this is the wrong :
HTTP Error 404.0 - Not Found
localhost --- >/assets/json/66016.geojson?callback=jQuery152048599341535009444_1366340277133&_=1366340277237
Try this
$.getJSON("/assets/json/66016.geojson",
"callback=?",
Sorry guys, finnaly i get my answer this is the solve :
$.getJSON("assets/json/66016.geojson",
"callback=?",
just erase "callback=?",
$.getJSON("/assets/json/66016.geojson",
Related
I can't solve this problem:
We have developed a webmapping application.
We use OpenLayers version 6 and Geoserver 2.18, and PostGis 3.0.2
Loading a WFS layer on openlayers is no problem.
On Openlayers, I tried to edit (add new vector) this layer (wfs-t) but save failed.
Editing this layer (wfs-t) on Qgis is going well.
here are the code blocks:
//variables
var its_typeName ='reception:fak_test';
var url_NS = 'http://localhost:8080/geoserver';
var url_wfs ='http://localhost:8080/geoserver/reception/ows?service=WFS&version=1.0.0';
var fak_draw;
var formatWFS = new ol.format.WFS();
var formatGML = new ol.format.GML3({
featureNS: url_NS,
featureType: its_typeName,
srsName: 'EPSG:4326'
//srsName: "EPSG:3857"
});
var transactWFS = function(p,f) {
f.unset('bbox', true);
switch(p) {
case 'insert':
node = formatWFS.writeTransaction([f],null,null,formatGML);
break;
case 'update':
node = formatWFS.writeTransaction(null,[f],null,formatGML);
break;
case 'delete':
node = formatWFS.writeTransaction(null,null,[f],formatGML);
break;
}
s = new XMLSerializer();
str = s.serializeToString(node);
console.log(str);
// send data
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
alert(request.responseText);
}
}
request.open("POST", url_wfs, true);
request.send(str);
}
// parameter of layer
var PolygonStyle = [
new ol.style.Style({
stroke: new ol.style.Stroke({ color: '#EC1B0C', width: 3,}),
fill: new ol.style.Fill({ color: 'rgba(0, 0, 255, 0.1)',}),
})
];
// to load wfs on OpenLayers
function test_wfs_t(){
var url = url_wfs
+ '&request=GetFeature'
+ '&typeName=' + its_typeName
+ '&outputFormat=application/json';
fetch(url)
.then((response) => response.text())
.then((data) => {
//console.log(data);
getItsAttributs_db(data);
});
}
function getItsAttributs_db(xData)
{
//get its infos to post in the new feature
var JSON_received = JSON.parse(xData);
var len_draw = JSON_received.features.length;
var xid = len_draw + 1;
var nom = "xxx";
var custom_lab = "next";
var descriptio = "bla bla";
var xcouleur= "#FF0000";
// convert to GeoJSON
const vectorSource = new ol.source.Vector({
features: new ol.format.GeoJSON().readFeatures(xData, {
dataProjection: 'EPSG:4326',
featureProjection: 'EPSG:3857'
}),
});
// init vector to load on map
var fak_Vector = new ol.layer.Vector({
source: vectorSource,
style: PolygonStyle
});
var its_source = fak_Vector.getSource();
// load on map
map.addLayer(fak_Vector);
//remove old draw
map.removeInteraction(fak_draw);
//add new draw
draw_boo_wfst = true;
fak_draw = new ol.interaction.Draw({
type: 'MultiPolygon',
source: its_source
});
map.addInteraction(fak_draw);
// on end of draw
fak_draw.on('drawend', function(e) {
//add its properties
var draw_wfst = e.feature;
draw_wfst.setProperties(create_gfc_Attributs_view(xid, nom, descriptio, custom_lab, xcouleur));
// try to send to database
transactWFS('insert', draw_wfst);
});
}
// to create attributs of the new feature
function create_gfc_Attributs_view(xid, nom, descriptio, custom_lab, xcouleur){
var xTable = {};
xTable.id = xid;
xTable.name = nom;
xTable.descriptio = descriptio;
xTable.custom_lab = custom_lab;
xTable.color = xcouleur;
// callback
return xTable;
}
PostgreSQL syntax :
-- Structure of postgis
CREATE TABLE public.fak_test
(
id integer NOT NULL DEFAULT nextval('track_store.fak_test_id_seq'::regclass),
geom geometry(MultiPolygon,4326),
name character varying(254) COLLATE pg_catalog."default",
descriptio character varying(254) COLLATE pg_catalog."default",
custom_lab character varying(254) COLLATE pg_catalog."default",
color character varying(254) COLLATE pg_catalog."default",
CONSTRAINT fak_test_pkey PRIMARY KEY (id)
)
GRANT ALL ON TABLE public.fak_test TO myuser;
CREATE INDEX sidx_fak_test_geom
ON public.fak_test USING gist
(geom)
TABLESPACE pg_default;
Output of GML
<Transaction xmlns="http://www.opengis.net/wfs" service="WFS" version="1.1.0"
xsi:schemaLocation="http://www.opengis.net/wfs http://schemas.opengis.net/wfs/1.1.0/wfs.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Insert>
<reception:fak_test xmlns:reception="http://localhost:8080/geoserver">
<reception:geometry>
<MultiPolygon xmlns="http://www.opengis.net/gml" srsName="EPSG:4326">
<polygonMember>
<Polygon srsName="EPSG:4326">
<exterior>
<LinearRing srsName="EPSG:4326">
<posList srsDimension="2">
-2144007.8418341065 5288167.744512376 -2144040.7892421824 5289040.850826394 -2145259.8433409994 5288645.48192948 -2144007.8418341065 5288167.744512376
</posList>
</LinearRing>
</exterior>
</Polygon>
</polygonMember>
</MultiPolygon>
</reception:geometry>
<reception:id>5</reception:id>
<reception:name>xxx</reception:name>
<reception:descriptio>bla blax</reception:descriptio>
<reception:custom_lab>suite</reception:custom_lab>
<reception:color>#FF0000</reception:color>
</reception:fak_test>
</Insert>
</Transaction>
Response from server:
<?xml version="1.0" encoding="UTF-8"?>
<ows:ExceptionReport xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:ows="http://www.opengis.net/ows"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.0.0"
xsi:schemaLocation="http://www.opengis.net/ows http://localhost:8080/geoserver/schemas/ows/1.0.0/owsExceptionReport.xsd">
<ows:Exception exceptionCode="InvalidParameterValue">
<ows:ExceptionText>org.geotools.referencing.operation.projection.PointOutsideEnvelopeException: -2144007.8418341065 outside of (-180.0,180.0)
Parsing failed for LinearRing: org.geoserver.wfs.WFSException: org.geotools.referencing.operation.projection.PointOutsideEnvelopeException: -2144007.8418341065 outside of (-180.0,180.0)
org.geotools.referencing.operation.projection.PointOutsideEnvelopeException: -2144007.8418341065 outside of (-180.0,180.0)
-2144007.8418341065 outside of (-180.0,180.0)</ows:ExceptionText>
</ows:Exception>
</ows:ExceptionReport>
Where is the problem?
Thank you
You are lying to GeoServer and it doesn't like it. You are sending coordinates that are not in lat/lon but claiming that they are.
<Polygon srsName="EPSG:4326">
<exterior>
<LinearRing srsName="EPSG:4326">
<posList srsDimension="2">
-2144007.8418341065 5288167.744512376 -2144040.7892421824 5289040.850826394 -2145259.8433409994 5288645.48192948 -2144007.8418341065 5288167.744512376
</posList>
</LinearRing>
</exterior>
</Polygon>
I don't know what projection your map is in, but I'd guess it is Web Mercator (EPSG:3857) so you should either set that in the data you send or reproject the polygon to ESPG:4326 before you send it.
I pass php $var into Javascript from controller. $var has fetched addresses from DB. And i put it in Javascript. Now i can see the addresses in the console. No problem with that, I don't know why syntax error pop up too.
This is how I insert it into JS.
function initMap(){
var options = {
zoom:8,
center:
'{!! $estates[0]->address !!}'
}
var map = new google.maps.Map(document.getElementById("map"), options);
var marker = new google.maps.Marker({
position:
#foreach($estates as $addr)
'{!! $addr->address !!}',
#endforeach
map:map
});
var infoWindow = new google.maps.InfoWindow({
content:'content here'
});
marker.addListener('click', function () {
infoWindow.open(map, marker);
});
}
my foreach running without a problem I can see the addreses in the console but also at this line: '{!! $estates[0]->address !!}' error pops up too. Actually I am seeing the address not this line.
error is this:
Uncaught SyntaxError: Invalid or unexpected token
Do you have any idea? am I making syntax mistake. But if do that then how can I retrieving the addresses at the console?
Also having this error too at the same line:
Undefined variable: estates (View:
/var/www/html/laravel/resources/views/layouts/app.blade.php) (View:
/var/www/html/laravel/resources/views/layouts/app.blade.php)
Controller
public function index()
{
$estates = DB::table("allestates")
->get();
return view("home", compact('estates'));
}
the topic is different the duplicated ones. it's not pure JS i am working with Laravel.
I think one of the addresses contains the ' character. To avoid it use the addslashes function. You could do that in the controller:
public function index()
{
$estates = DB::table("allestates")->get()->map(function($estate) {
$estate->address = addslashes($estate->address);
return $estate;
});
return view("home", compact('estates'));
}
And the according js would be:
var options = {
zoom:8,
center: new google.maps.LatLng({{$estates[0]->lat}}, {{$estates[0]->long}});
}
Because you have multiple addresses, it means you will have multiple markers too. That being said your code should look something like:
function initMap(){
var options = {
zoom:8,
center: new google.maps.LatLng({{$estates[0]->lat}}, {{$estates[0]->long}});
}
var map = new google.maps.Map(document.getElementById("map"), options);
var infoWindow = new google.maps.InfoWindow({
content:'content here'
});
var markers = [];
#foreach ($estates as $key => $estate)
markers[{{$key}}] = new google.maps.Marker({
position: new google.maps.LatLng({{$estate->lat}}, {{$estate->long}});
map: map
});
markers[{{$key}}].addListener('click', function () {
infoWindow.open(map, markers[{{$key}}]);
});
#endforeach
}
You can use php variables inside laravel blade files as
var options = {
zoom:8,
center:
'{{$estates[0]->address}}'
}
I'm having an issue accessing a json file from a js script in a Laravel project.
I am using the Google maps API to add markers to a map, which are all currently hard-coded because I can only seem to access the json from within a listener function.
I am fully able to access my json through the placeMarker click listener, but when i try to make the "otherPlace" using json values, the values cannot be found. Not sure what's going on here.
Sorry for the likely noob question but I am stumped and couldn't find any similar questions.
Map script Example:
function myMap() {
var mapProp= {
center:new google.maps.LatLng(44.5458062,-83.54936229999996),
zoom:8,
};
var map = new google.maps.Map(document.getElementById("googleMap"),mapProp);
var place = new google.maps.LatLng(44.453,-83.45773609999998);
var placeMarker = new google.maps.Marker({position: place});
var otherPlace = new google.maps.LatLng(json.locations[4].lat,json.locations[4].lng);
var otherPlaceMarker = new google.maps.Marker({position: otherPlace});
placeMarker.setMap(map);
otherPlaceMarker.setMap(map);
placeMarker.addListener('click', function() {
map.setZoom(13);
map.setCenter(placeMarker.getPosition());
console.log(json.locations[5].address);
var infowindow = new google.maps.InfoWindow({
//content: json.locations[5].name + "\r\nAddress: " + json.locations[5].address
});
infowindow.setContent(
"<p>" + json.locations[5].name + "<br />" + json.locations[5].address + "<br/> <a href='#'>Get Directions</a> </p>"
);
infowindow.open(map,placeMarker);
});
}
In my controller I grab the json file and pass it to the view
public function locations() {
$path = storage_path() . "/json/locations.json";
$json = json_decode(file_get_contents($path), true);
return view('home/locations', compact('json'));
}
In my locations.blade.php I add the map script and pass the json to javascript
#section('scripts')
<script src="/js/locationsMap.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?key={{ env('APP_GOOGLE_MAPS') }}&callback=myMap"></script>
<script>
var json = {!! json_encode($json) !!};
</script>
#endsection
Try removing var from var json if that doesn't work, put your function below json = {!! json_encode($json) !!}; and try then
I have some js code, that I would like to move to an external js file, but the script references razor syntax (url path) in the View.
Here is the script:
function getStops() {
var url = $('#map').data('request-url');
$.getJSON(url,
function (data) {
var marker = [];
$.each(data,
function (i, item) {
marker.push({
'location': new google.maps.LatLng(item.Latitude2, item.Longitude2),
'map': map,
'weight': item.Difference,
'radius': 10
});
});
var pointArray = new google.maps.MVCArray(marker);
heatmap = new google.maps.visualization.HeatmapLayer({
data: pointArray
});
heatmap.setMap(map);
});
};
// get Driving and show on layer
function getDriving() {
var url = $('#map').data('request-url2');
$.getJSON(url,
function (data) {
var marker = [];
$.each(data,
function (i, item) {
marker.push({
'location': new google.maps.LatLng(item.Latitude2, item.Longitude2),
'map': map,
'weight': item.Speed,
'radius': 10
});
});
var pointArray = new google.maps.MVCArray(marker);
heatmap = new google.maps.visualization.HeatmapLayer({
data: pointArray
});
heatmap.setMap(map);
});
I know about data-request-url that I can reference in an element (in my case it's a div).
So I wrote it like this in the View:
<div id="map" data-request-url="#Url.Action("GetStops", "Home")" data-request-url2="#Url.Action("Driving", "Home")">
Is this the right way to go, or can it be done in other way?
I am trying to add markers to my Google map dynamically using a combination of ajax and php.
The first part of the code sends the latlng to the php file. The php file then returns the marker location needed.
When I alert the return part (ALERT TEST TO ENSURE PHP PROCESSED DATA CORRECTLY), it looks OK, but I cant seem to add the markers from the return on to my map.
See code below.
//SEND DATA TO URL (send to php file)
//RETURN DATA FOR PLACE MARKERS (this is what the return php file produces)
Many thanks,
//SEND DATA TO URL
var xmlHttp = getXMLHttp();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4) {
HandleResponse(xmlHttp.responseText);
}}
xmlHttp.open("POST",'MYPHPFILE',true);
xmlHttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlHttp.send("LATLON="+strLAT);
//RETURN DATA FOR PLACE MARKERS
var wxlatlng = new google.maps.LatLng(52,1);
var marker = new google.maps.Marker({
position: wxlatlng,
map: map,
icon: '../../icons/flags/traffic_light_red.png',
title: 'TEST', });
//RETURN DATA FOR PLACE MARKERS
var wxlatlng = new google.maps.LatLng(52,1.1);
var marker = new google.maps.Marker({
position: wxlatlng,
map: map,
icon: '../../icons/flags/traffic_light_red.png',
title: 'TEST', });
//ALERT TEST TO ENSURE PHP PROCESSED DATA CORRECTLY
function HandleResponse(response) {
document.getElementById('ResponseDiv').innerHTML = response;
alert($('#ResponseDiv').text());
}
The answer i found for my question was to use the php file to create the markers xml file and load the xml file via jQuery response
See code below;
jQuery.get(YOURXMLFILE, function(data) {
jQuery(data).find("marker").each(function() {
var eachMarker = jQuery(this);
var markerCoords = new google.maps.LatLng(
parseFloat(eachMarker.find("Lat").text()),
parseFloat(eachMarker.find("Lng").text())
);
var header = eachMarker.find("title").text();
var content = eachMarker.find("Content").text();
var wxicon = eachMarker.find("icon").text();
//--------------------------------------------------------------------------
marker = new google.maps.Marker({
position: markerCoords,
icon: wxicon,
map: map,
animation: google.maps.Animation.DROP,
title: header,
});
});
});