I'm trying to find method to merge many polygon ( >100 ) in order to have only 1 polygon to have just the border of the merged polygon, not border for all "little" polygon
I import coordinates from JSON file and I use this code to render each polygon:
var thisUcVar<?php echo $nb_fichier ?>;
var thisAgencyVar<?php echo $nb_fichier ?>;
var thisListAgencyVar;
var thisUcColor;
$.getJSON("<?php echo("test/". $fichier); ?>", function(json1) {
var i=0;
var coordUc = [];
var thisUc = json1;
thisUcVar<?php echo $nb_fichier ?> = thisUc[0].name;
thisAgencyVar<?php echo $nb_fichier ?> = thisUc[0].agency;
thisUcColor = thisUc[0].color;
$.each(json1, function(key, data){
i = 0;
$.each(data.coordinates, function(key, data){
coordUc.length = 0;
$.each(data, function(key, data){
var innerCoordUc = {"lat": data[1], "lng": data[0] };
coordUc[i] = innerCoordUc;
i++;
});
var uc = new google.maps.Polygon({
title: i,
strokeWeight: 1,
fillColor: thisUcColor,
paths: coordUc,
zIndex: 10
});
uc.setMap(map);
map.addListener('zoom_changed',function(){
if(map.getZoom()>=10){
uc.set('zIndex', 90);
}else{
uc.set('zIndex', 10);
}
});
uc.addListener('click', function() {
$(".layer").html("<h1>" + thisUcVar<?php echo $nb_fichier ?> + "</h1><ul></ul>");
$.each(thisAgencyVar<?php echo $nb_fichier ?>, function(key, data){
listThisAgencyVar = data.name;
$(".layer").append("<li>" + uc.title + listThisAgencyVar + "</li>");
});
if(map.getZoom() >= 10){
map.setZoom(11);
map.setCenter(uc.getBounds().getCenter());
}
});
if (!google.maps.Polygon.prototype.getBounds) {
google.maps.Polygon.prototype.getBounds=function(){
var bounds = new google.maps.LatLngBounds()
this.getPath().forEach(function(element,index){bounds.extend(element)})
return bounds;
}
}
});
});//fin de boucle json1
});
Result is like image below:
And here one of the JSON files that I'm using to generate each polygons.
JSON used to generate polygons group
I search everywhere and I didn't find any way to merge many polygons in one big ...
Thanks a lot
A solution that might work is using the Turf library. In particular, it has a union method that does exactly what you want (merge multiple polygons into one that corresponds to the union of the polygons).
However, this library uses the Geojson standard format so you will need to convert your data into this standard.
If you can use this format, it will also help you to display the data on the map using a DataLayer and the loadGeoJson method from Google Maps API.
Related
I'm using this code to map power transformers on a leaflet map, but unfortunately when the map loads I don't find my data displayed. Can you please help me identify some problems(if any) in my code. I must admit that I'm new to web mapping so I just need some help here.
Here is the javascript code I'm using:
//global variables
var map,
fields = ["tx_id", "owner", "kva_rating", "prim_voltage", "sec_voltage", "serial_no", "area_name"],
autocomplete = [];
$(document).ready(initialize);
function initialize(){
$("#map").height($(window).height());
map = L.map("map", {
center: L.latLng(-0.7166700, 36.4359100),
zoom: 10
});
var tileLayer = L.tileLayer('https://api.tiles.mapbox.com/v4/mapbox.streets/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoicmFqYWJueWFtYnUiLCJhIjoiY2lqbTB4cnpiMDA4bnZhbHh3Znl2aDAwZiJ9.YC_iahav7t9GPl-7XgB-yQ', {
attribution: 'Network Design © Rajab Inc., Map data © OpenStreetMap contributors, | Map Tiles: CC-BY-SA, Imagery © Mapbox',
maxZoom: 19,
minZoom: 1,
id: 'rajabnyambu.oo91e3ga',
accessToken: 'pk.eyJ1IjoicmFqYWJueWFtYnUiLCJhIjoiY2lqbTB4cnpiMDA4bnZhbHh3Znl2aDAwZiJ9.YC_iahav7t9GPl-7XgB-yQ'
}).addTo(map);
//next: add features to map
getData();
};
function getData(){
$.ajax("getData.php", {
data: {
table: "transformer",
fields: fields
},
success: function(data){
mapData(data);
}
})
};
function mapData(data){
//remove existing map layers
map.eachLayer(function(layer){
//if not the tile layer
if (typeof layer._url === "undefined"){
map.removeLayer(layer);
}
});
//create geojson container object
var geojson = {
"type": "FeatureCollection",
"features": []
};
//split data into features
var dataArray = data.split(", ;");
dataArray.pop();
//console.log(dataArray);
//build geojson features
dataArray.forEach(function(d){
d = d.split(", "); //split the data up into individual attribute values and the geometry
//feature object container
var feature = {
"type": "Feature",
"properties": {}, //properties object container
"geometry": JSON.parse(d[fields.length]) //parse geometry
};
for (var i=0; i<fields.length; i++){
feature.properties[fields[i]] = d[i];
};
//add feature names to autocomplete list
if ($.inArray(feature.properties.featname, autocomplete) == -1){
autocomplete.push(feature.properties.featname);
};
geojson.features.push(feature);
});
//console.log(geojson);
//activate autocomplete on featname input
$("input[name=area_name]").autocomplete({
source: autocomplete
});
var mapDataLayer = L.geoJson(geojson, {
pointToLayer: function (feature, latlng) {
var markerStyle = {
fillColor: "#CC5600",
color: "#CAF",
fillOpacity: 0.5,
opacity: 0.8,
weight: 1,
radius: 8
};
return L.circleMarker(latlng, markerStyle);
},
onEachFeature: function (feature, layer) {
var html = "";
for (prop in feature.properties){
html += prop+": "+feature.properties[prop]+"<br>";
};
layer.bindPopup(html);
}
}).addTo(map);
};
my getData.php file works well so I guess the problem lies within the javascript file. Here is the getData.php:
require ('networkdbinfo.php');
$dbc = pg_connect( "$host $port $dbname $credentials" );
if(!$dbc) {
echo "Not connected : " . pg_error();
exit;
}
// Get the table and fields data
$table= 'transformer';
$fields = ["tx_id", "owner", "kva_rating", "prim_voltage", "sec_voltage", "serial_no", "area_name"];
// Turn fields array into formatted string
$fieldstr="";
foreach ($fields as $i=> $field) {
$fieldstr=$fieldstr . "l.$field,";
}
// Get the geometry as geojson in EPSG:900913
$fieldstr=$fieldstr . "ST_AsGeoJSON(ST_Transform(l.geom, 900913))";
// Create basic SQL statement
$sql="SELECT $fieldstr FROM $table l";
//if a query, add those to the sql statement
if (isset($_GET['area_name'])){
$area_name = $_GET['area_name'];
$distance = $_GET['distance'] * 1000; //change km to meters
//join for spatial query - table geom is in EPSG:900913
$sql = $sql . " LEFT JOIN $table r ON ST_DWithin(l.geom, r.geom, $distance) WHERE r.area_name = '$area_name';";
}
// echo $sql;
// Send the query
if (!$response=pg_query($dbc, $sql)) {
echo "A query error occurred.\n";
exit;
}
// Echo the data back to the DOM
while ($row=pg_fetch_row($response)) {
foreach ($row as $i=> $attr) {
echo $attr.", ";
}
echo ";";
}
?>
You probably have the same issue as there:
Json file dosen't show up in google chrome
I.e. opening your page from File System in Chrome browser.
The solutions proposed in that post are to set up a local server or to open Chrome with specific parameters.
But you should be able to test it directly with Firefox instead.
I refer to the question Polygon "Drawing and Getting Coordinates with Google Map API v3" and the code by jhawes which works fine; BUT I've struggle to post the lat/lng-values to a DB using php.
In other scripts with single coordinates I use the following (whereas the variables "BlattNr, Quadrant, MTBlat, MTBlng, Qmlat, Qmlng" are of no interest for that question):
function saveData(BlattNr, Quadrant, MTBlat, MTBlng, Qmlat, Qmlng) {
var latlng = marker.getPosition();
window.location.href = "schritt_2.php?lat=" + latlng.lat() +
"&lng=" + latlng.lng() + "&MTBNr=" + BlattNr + "&Quadrant=" + Quadrant + "&MTBlat=" + MTBlat + "&MTBlng=" + MTBlng + "&Qmlat=" + Qmlat + "&Qmlng=" + Qmlng;
marker.setMap(null);
}
With this I can post the lat and lng of the single point coordinate - but how to pass the multiple lat and lng of various points? I don't know how to define the variable and how to construct the "saveData" function...
Many thanks in advance for any help :-)
Okay, I copy/pasted the code that jhawes put in jsFiddle
I added a few things.
add jQuery
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Save_data
function save_data() {
var data = [];
var len = myPolygon.getPath().getLength();
for (var i = 0; i < len; i++) {
data.push([myPolygon.getPath().getAt(i).lat(), myPolygon.getPath().getAt(i).lng()]);
}
// send data to the server
$.ajax({
url: 'save.php?p=' + JSON.stringify(data),
success: function (message) {
$('#ajaxresponse').html(message);
}
});
}
A button and a display div. Put them somewhere at the bottom of the markup.
<input type="button" onclick="save_data()" value="SAVE">
<div id="ajaxresponse"></div>
Server side: I don't do much here; I'm sure you can handle it.
save.php
<?php
if (isset($_GET['p'])) {
$locations = json_decode($_GET['p'], true);
echo print_r($locations, true) . '<br>';
echo "let's print the second point: lat=" . $locations[1][0] . ", lng=" . $locations[1][0];
}
?>
I'm trying to show data from visitors inside a map created using jvectormap plugin.
This is driving me crazy, i can not load the data through ajax, if i put the data manually it works.
So far i have this:
map.php
$datos = array();
$link->set_charset("utf8");
$sql = $link->query("SELECT SUM(ID) as visitors, state FROM visitors WHERE state != '' GROUP BY state");
while($row = $sql->fetch_row()){
$ss = $link->query("SELECT * FROM states WHERE state = '".$row[1]."'");
$rr = $ss->fetch_row();
$datos[] = array("ccode" => $rr[2], "visits" => $row[0]);
}
$data = array("countries" => $datos);
echo json_encode($data,JSON_NUMERIC_CHECK);
This returns the following data:
{"countries":[{"ccode":"VE-A","visits":81},{"ccode":"VE-L","visits":24}]}
Now the function to load the map:
function cargaMapa(){
//jvectormap data
$.post("ajax/map.php",{},function(mapa){
var dataC = eval(mapa);
//var dataC = {"countries":[{"ccode":"VE-A","visits":81},{"ccode":"VE-L","visits":24}]};
var countryData = [];
//for each country, set the code and value
$.each(dataC.countries, function() {
countryData[this.ccode] = this.visits;
console.log("Estado: "+this.ccode+" Visitas: "+this.visits);
});
//World map by jvectormap
$('#world-map').vectorMap({
map: 've_mill_en',
backgroundColor: "#fff",
regionStyle: {
initial: {
fill: '#e4e4e4',
"fill-opacity": 1,
stroke: 'none',
"stroke-width": 0,
"stroke-opacity": 1
}
},
series: {
regions: [{
values: countryData,
scale: ["#3c8dbc", "#2D79A6"], //['#3E5E6B', '#A6BAC2'],
normalizeFunction: 'polynomial'
}]
},
onRegionLabelShow: function(e, el, code) {
//search through dataC to find the selected country by it's code
var country = $.grep(dataC.countries, function(obj, index) {
return obj.ccode == code;
})[0]; //snag the first one
//only if selected country was found in dataC
if (country != undefined) {
el.html(el.html() + ': ' + country.ccode + country.visits + ' visitas');
}
}
});
});
}
As you can see in the function i have the var dataC, if i load in there the array coming from map.php it gives me Uncaught SyntaxError: Unexpected token : but if copy and paste the result of map.php into the var dataC it works pretty good.
How can i solve this?
I appreciate any help
Thanks
I figured it out, just changed $.post for $.getJSON and the magic began
I'm building something so I can parse latitudes and longitudes from an XML file. The problem is that I have a users with multiple lat and lng (used for markers on google maps) coordinates and only the first coordinate is saved in the array. I would like to have every coordinate in the array. It looks like that the foreach function isn't working properly
Here is the ajax call to the php file where I parse the xml file. And also test if the parsed data is working with json.
<html>
<head>
<script type="text/javascript" src="jquery-2.1.0.js"></script>
<script>
$(function()
{
$.ajax(
{
type:"GET",
url:"leesstudent.php",
success:callback
}
);
});
function callback(data,status)
{
alert(data);
var jsArr = JSON.parse(data);
var coordinates = new Array();
alert(jsArr[0]);
for(var i=0;i<jsArr.length;i++)
{
$("#message").append("<p>" + jsArr[i].latitude + " " + jsArr[i].longitude + "</p>");
}
}
</script>
</head>
<body>
<div id="message">
Message..
</div>
</body>
The php file where I parse the xml, from my opinion the foreach doesn't work
$xml = simplexml_load_file("Database.xml");
$coordinaten = array();
$teller = 0;
foreach($xml->user as $item)
{
$coordinaten[$teller]["latitude"] = (string)$item -> latitude;
$coordinaten[$teller]["longitude"] = (string)$item -> longitude;
$teller++;
}
print json_encode($coordinaten);
the xml code
<root>
<user>
<username>$2y$11$6SxUsvoDGlwm3Ji6BcnzCu/QyUWNy09Ny/.M9rXIpvImgJ1igJppy</username>
<password>$2y$11$6SxUsvoDGlwm3Ji6BcnzCu7hIhAyNKtdlui1.oMdK4gQJnkZrL/Ky</password>
<latitude>50.74688365485319</latitude><longitude>5.0701904296875</longitude>
<latitude>51.09662294502995</latitude><longitude>4.9713134765625</longitude>
</user>
</root>
I only get the first latitude and longitude data, I would like have both (and in the future even more).
Your foreach loop isn't correct.
He will loop trough the users but never loop trough your coordinats!
foreach($xml->user as $item){
$teller = 0;
foreach($item -> latitude as $test )
{
$coordinaten[$teller]["latitude"] = (string)$test;
$teller++;
}
$teller = 0;
foreach($item -> longitude as $test2)
{
$coordinaten[$teller]["longitude"] = (string)$test2;
$teller++;
}
}
I am using this code to get users full address info
function getGeo() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (a) {
$("#geoLoc").html("Determing your location..");
$.post("https://mysite.com/getloc.php?l=" + a.coords.latitude + "," + a.coords.longitude, function (b) {
var c = jsonParse(b);
geo_adres = c.results[0].formatted_address;
latitude = a.coords.latitude;
longitude = a.coords.longitude;
$("#geoLoc").html(c.results[0].formatted_address);
$("#geoLoc").show("slow")
})
}, function (a) {
alert(geolocationErrorMessages[a.code])
}, {
enableHighAccuracy: true,
maximumAge: 12e4
});
return false
} else {
alert("Your browser doesn't support geo-location feature...")
}
}
EDIT:
getloc.php contains this codes (c var in javascript)
$data = file_get_contents("https://maps.googleapis.com/maps/api/geocode/json?latlng=". $_GET['l'] ."&sensor=false");
print $data;
Actually all i want is to get users city and country info like that city, country
How should i change this one c.results[0].formatted_address to achieve that ?
Try this working php code, i hope this is going to help you a lot :) and let mew know in case of any query --
<?php
$data = file_get_contents("http://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&sensor=false");
$jsonnew =json_decode($data,true);
echo "<pre>";
print_r($jsonnew['results'][7]['address_components'][2]['long_name']);
echo "<pre>";
print_r($jsonnew['results'][6]['address_components'][2]['long_name']);
You shouldn't need your getloc PHP script. The Maps Javascript API includes a Geocoder class.