Format GeoJson LineString to Dashed - javascript

This is my GeoJson :
{
"type" : "FeatureCollection",
"created" : "2014/07/08 03:00:55 GMT",
"announced_date" : "2017/07/10 03:00:55 GMT",
"features" : [{
"type" : "Feature",
"properties" : {
"name" : "n18",
"analized_date" : "2013/07/08 10:00:00 GMT"
},
"geometry" : {
"type" : "GeometryCollection",
"geometries" : [{
"type" : "Point",
"coordinates" : [134.7, 37.3]
}, {
"type" : "LineString",
"coordinates" : [[134.7, 37.3], [134.6, 37.1]]
}
]
}
}]
}
I can display it in normal line but I want display as dashed line .
I google and there is a way : use Polyline but I don't know how to convert it to Polyline .
Please help . Thank you :) .

To make the poly line dashed, you have to create a native google.maps.Polyline object. One way to do that is to use the data layer to load the GeoJSON, then use its methods to create the polyline from the GeoJSON:
code snippet:
function initialize() {
// Create a simple map.
map = new google.maps.Map(document.getElementById('map-canvas'), {
zoom: 8,
center: {
lat: 37,
lng: 134
}
});
google.maps.event.addListener(map, 'click', function() {
infowindow.close();
});
// process the loaded GeoJSON data.
google.maps.event.addListener(map.data, 'addfeature', function(e) {
if (e.feature.getGeometry().getType() === 'GeometryCollection') {
var geometry = e.feature.getGeometry().getArray();
for (var i = 0; i < geometry.length; i++) {
if (geometry[i].getType() === 'Point') {
map.setCenter(geometry[i].get());
new google.maps.Marker({
map: map,
position: geometry[i].get()
});
} else if (geometry[i].getType() === 'LineString') {
new google.maps.Polyline({
map: map,
path: geometry[i].getArray(),
// make the polyline dashed. From the example in the documentation:
// https://developers.google.com/maps/documentation/javascript/examples/overlay-symbol-dashed
strokeOpacity: 0,
icons: [{
icon: {
path: 'M 0,-1 0,1',
strokeOpacity: 1,
scale: 4
},
offset: '0',
repeat: '20px'
}]
})
}
}
}
map.data.setMap(null);
});
map.data.addGeoJson(data);
}
google.maps.event.addDomListener(window, 'load', initialize);
var data = {
"type" : "FeatureCollection",
"created" : "2014/07/08 03:00:55 GMT",
"announced_date" : "2017/07/10 03:00:55 GMT",
"features" : [{
"type" : "Feature",
"properties" : {
"name" : "n18",
"analized_date" : "2013/07/08 10:00:00 GMT"
},
"geometry" : {
"type" : "GeometryCollection",
"geometries" : [{
"type" : "Point",
"coordinates" : [134.7, 37.3]
}, {
"type" : "LineString",
"coordinates" : [[134.7, 37.3], [134.6, 37.1]]
}
]
}
}]
};
html,
body {
height: 100%;
margin: 0px;
padding: 0px;
width: 100%;
}
#map-canvas {
height: 100%;
width: 100%;
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map-canvas"></div>

Related

How to color GeoJson polygons using another api?

I have a GeoJson map file with province ids and coordinates , also I am using another api which tells the color of each province id . I want to set fillColor of each polygon accordingly
my GeoJson file (just the first polygon as an example):
[
{
"type" : "FeatureCollection",
"features" : [
{
"type" : "Feature",
"id" : 0,
"regionColor": "orangeColor",
"geometry" : {
"type" : "Polygon",
"coordinates" : [...]
},
"properties" : {
"FID" : 0,
"FID_1" : 0
}
}
]
my API (imported as mockData):
{
"colors": [
{
"id": "0",
"countryColor": "red"
},
{
"id": "1",
"countryColor": "orange"
},
{
"id": "2",
"countryColor": "yellow"
}
]
}
my code :
<template>
<div class="container">
<div id="mapContainer">
</div>
</div>
</template>
<script>
import "leaflet/dist/leaflet.css";
import L from "leaflet";
import geojson from "../components/provinces.json"
import mockData from "./test.json"
export default{
name: "locationMap",
data() {
return{
center: [32.87255939010237, 53.781741816799745],
}
},
methods: {
setupLeafletMap: function () {
const mapDiv = L.map("mapContainer").setView(this.center, 5);
L.tileLayer(
'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
{
attribution: '© <a target="_blank" href="http://osm.org/copyright">OpenStreetMap</a> contributors',
// maxZoom: 18,
}
).addTo(mapDiv);
var myStyle = {
"fillColor": "#818181",
"color": "black",
"weight": 2,
"opacity": 0.65,
"fillOpacity": 0.6
};
L.geoJSON(geojson,{
style: myStyle,
}
}
}
mounted() {
this.setupLeafletMap()
console.log(mockData.colors[1].id)
},
}
</script>
L.geoJSON accepts a style function to dynamically apply styles based on each feature. You can write a style function that maps the feature ID to the color in your dataset. For example:
L.geoJSON(geoJSONData, {
// The style function receives each feature from your GeoJSON dataset.
// You can access the feature's properties to lookup the color.
style: function (feature) {
const fid = feature.properties.FID,
color = mockData.colors.find((color) => parseInt(color.id) === fid);
console.debug(`Feature with id ${fid} has now color ${color.countryColor}`);
return {
fillColor: color.countryColor,
color: "black",
weight: 2,
opacity: 0.65,
fillOpacity: 0.6
};
}
}).addTo(map);
I created an example with your code and some sample data as a reference, check it out here: https://codepen.io/strfx/pen/XWYNrBM
Hope this helps!

Google maps dragging marker adds border to another marker

I've just tried adding a main draggable marker on to the map. The issue I'm facing is that as soon as you drag that marker in black it creates a blue outline to one of the existing markers that are already placed on the map. I have no idea why it does this. I've isolated the bit of code where it's actually doing this, which is the click event listener that I've added to each marker, as soon as I remove this little snippet of code, it doesn't add a blue outline to any marker anymore. It's important to note, I've also tried commenting out the calls to the two inner function on this click handler however that doesn't seem to fix the issue, so it can't be those functions that are the cause.
It's also not a browser issue as the blue outline appears on both safari and chrome.
marker.addListener('click',
function() {
openCloseNav(true);
car_park_details(marker);
});
You can see the blue outline on the marker here (On the rightmost marker)
Most of the javascript I've added below.
var markers = [];
var geocoder;
var map;
var mainMarker;
function initMap() {
geocoder = new google.maps.Geocoder();
var defaultCoord = {
lat : 51.600960,
lng : -0.275770
};
map = new google.maps.Map(document.getElementById('map'), {
zoom : 15,
center : defaultCoord,
minZoom : 14,
streetViewControl : false,
controlSize : 33,
gestureHandling : 'greedy',
mapTypeControlOptions : {
mapTypeIds : []
},
styles : [ {
"featureType" : "all",
"elementType" : "all",
"stylers" : [ {
"hue" : "#008eff"
} ]
}, {
"featureType" : "road",
"elementType" : "all",
"stylers" : [ {
"saturation" : "0"
}, {
"lightness" : "0"
} ]
}, {
"featureType" : "transit",
"elementType" : "all",
"stylers" : [ {
"visibility" : "off"
} ]
}, {
"featureType" : "water",
"elementType" : "all",
"stylers" : [ {
"visibility" : "simplified"
}, {
"saturation" : "-60"
}, {
"lightness" : "-20"
} ]
} ]
});
mainMarker = new google.maps.Marker({
map,
position: defaultCoord,
draggable: true,
icon : {
url : 'mainmarker.png',
scaledSize : new google.maps.Size(30, 30),
origin : new google.maps.Point(0, 0),
}
});
google.maps.event.addListener(map, 'tilesloaded',
find_closest_markers);
google.maps.event.addListener(mainMarker, 'dragend',
find_closest_markers);
}
function geocodeEncapsulation(i) {
return (function(results, status) {
if (status == 'OK') {
var marker = new MarkerWithLabel({
map : map,
position : results[0].geometry.location,
icon : {
url : 'pin.png',
scaledSize : new google.maps.Size(40, 30),
//origin : new google.maps.Point(0, 0),
},
clickable: true,
labelContent : '£' + i.price.toFixed(2),
labelAnchor : new google.maps.Point(30, 35),
labelClass : "markerdesign",
labelInBackground : false,
title : i.name
});
marker.set("carpark", i);
marker.addListener('mouseover',
function() {
marker.set("labelClass",
"markerdesignhover");
});
marker.addListener('mouseout',
function() {
marker.set("labelClass", "markerdesign");
});
marker.addListener('click',
function() {
openCloseNav(true);
car_park_details(marker);
});
markers.push(marker);
} else {
//console.log(status);
}
});
}
Simplified Version On Fiddle, Drag the centre marker
http://jsfiddle.net/qn23wxmL/2/
Update:
Adding a separate click listener to the draggable marker solves the issue.
However I don't understand how this is working, if anyone can explain, that would be great.

Google Maps GeoJSON feature trigger click event

I have a featurecollection of features with their corresponding IDs like this:
"type"=>"Feature",
"id"=>"test_1",
"properties"=>array("desc"=>...
and want to trigger a click event from a button on the document so that the infowindow opens.
var featId = 'test_1';
map.event.trigger(featId, 'click');
but I'm getting
Uncaught TypeError: Cannot read property 'trigger' of undefined
The infowindow opens when I click on the polygon on the map.
Here's a JS fiddle.
I've also added a code snippet using stackoverflow's editor.
var mygeojson={
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
'id':'test_2',
"properties": {},
"geometry": {
"type": "Polygon",
"coordinates": [
[
[
0.5767822265625,
46.437856895024204
],
[
0.560302734375,
46.160809861457125
],
[
0.9118652343749999,
46.10370875598026
],
[
1.42822265625,
46.22545288226939
],
[
0.9118652343749999,
46.581518465658014
],
[
0.5767822265625,
46.437856895024204
]
]
]
}
},
{
"type": "Feature",
'id':'test_1',
"properties": {},
"geometry": {
"type": "Polygon",
"coordinates": [
[
[
1.9335937499999998,
46.98774725646568
],
[
1.8841552734374998,
46.73233101286786
],
[
2.581787109375,
46.53619267489863
],
[
2.8784179687499996,
46.71350244599995
],
[
3.065185546875,
47.00647991252098
],
[
2.3785400390625,
47.18597932702905
],
[
2.1917724609375,
47.60986653003798
],
[
1.9335937499999998,
46.98774725646568
]
]
]
}
}
]
};
function openinfo(target_featId)
{
//map.event.trigger(featId, 'click');
google.maps.event.trigger(map, 'click');
}
initpage = function()
{
var selected_id = 0;
console.log('html loaded');
//center lat/lon
var latlng = new google.maps.LatLng(46.315,0.467);
//map configutations
var myOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
scrollwheel: true,
};
map = new google.maps.Map(document.getElementById("themap"), myOptions);
map.data.addGeoJson(mygeojson);
map.data.setStyle(function(feature) {
//var SD_NAME = feature.getProperty('SD_NAME');
//var color = feature.getProperty('boja');
var featId = feature.getId();
var color = 'gray';
if(selected_id == featId)
{
color='#009900';
console.log('setting green for '+featId)
} else
{
color = 'gray';
console.log('setting gray for '+featId)
}
return {
fillColor: color,
strokeColor: color,
strokeWeight: 1
}
});
var infowindow = new google.maps.InfoWindow();
map.data.addListener('click', function(event) {
//var feat_desc = event.feature.getProperty("desc");
var featId = event.feature.getId();
map.data.forEach(function(feature2) {
if(featId == selected_id) feature2.setProperty('color','gray');
});
selected_id = featId;
var color = '#009900';
infowindow.setContent("<div style='width:150px; color: #000;'> litttle test "+featId+"</div>");
// position the infowindow on the marker
infowindow.setPosition(event.feature.getGeometry().getAt(0).getAt(0));
infowindow.open(map);
});
}
html { height: 100% }
body { height: 100%; margin: 0px; padding: 0px; background: #fff; color: #bbb; font-size: 13px; font-family: Arial;}
#themap { height:100%; }
<html>
<head>
<script type="text/javascript" src="https://maps.google.com/maps/api/js"></script>
</head>
<body onload="initpage()">
Open poly 1
Open poly 2<br /><br />
<div id="themap">
</div>
</body>
</html>
I've successfully fixed this by using:
function openinfo(target_featId)
{
google.maps.event.trigger(map.data,'click',target_featId);
}
and then had a new issue with the addListener function. the event.feature was undefined, so I fixed it with:if(!event.feature) event.feature=event; inside map.data.addListener('click', function(event) {

Using Javascript to extract the Latitude and Longitude from a kml field in a Google fusion table

I have a google fusion table that I am inserting data into that contains kml.
I need to query (or extract) the latitude and longitude from the kml column.
When I query the table I get data returned in this format:
{
"kind": "fusiontables#sqlresponse",
"columns": [
"description",
"name",
"geometry"
],
"rows": [
[
"\u003cimg alt=\"The North Fields\" class=\" tall\" src=\"https://d15mj6e6qmt1na.cloudfront.net/files/images/1501/0978/The_North_Fields_small.JPG\" style=\"float:left; padding: 0 3px 3px\" /\u003e\n by ctipp\u003cbr/\u003e\n \u003ca href=\"http://audioboom.com/boos/3260713-coastal-lagoon\"\u003eVisit on audioboom.com\u003c/a\u003e\n \u003chr style=\"clear:both\"/\u003e",
"Coastal Lagoon",
{
"geometry": {
"type": "Point",
"coordinates": [
-0.749484,
50.7627,
0.0
]
}
}
]
]
}
the above data is read into a javascript variable using a callback function and i need to know the correct syntax for extracting the latitude and longitude (ie -0.749484, 50.7627)
I've got this far:
success: function(data) {
var rows = data['rows'];
var desc = rows[0][0];
var name = rows[0][1];
but I'm stuck on the geometry field...
success: function(data) {
var rows = data['rows'];
var desc = rows[0][0];
var name = rows[0][1];
var latitude = rows[0][2].geometry.coordinates[1]; // KML is longitude, latitude
var longitude = rows[0][2].geometry.coordinates[0];
var data = {
"kind": "fusiontables#sqlresponse",
"columns": [
"description",
"name",
"geometry"
],
"rows": [
[
"\u003cimg alt=\"The North Fields\" class=\" tall\" src=\"https://d15mj6e6qmt1na.cloudfront.net/files/images/1501/0978/The_North_Fields_small.JPG\" style=\"float:left; padding: 0 3px 3px\" /\u003e\n by ctipp\u003cbr/\u003e\n \u003ca href=\"http://audioboom.com/boos/3260713-coastal-lagoon\"\u003eVisit on audioboom.com\u003c/a\u003e\n \u003chr style=\"clear:both\"/\u003e",
"Coastal Lagoon", {
"geometry": {
"type": "Point",
"coordinates": [-0.749484,50.7627,0.0]
}
}
]
]
};
function initialize() {
var infowindow = new google.maps.InfoWindow();
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 16,
center: {
lat: 50.7627,
lng: -0.749484
}
});
var latLng = new google.maps.LatLng(data.rows[0][2].geometry.coordinates[1],
data.rows[0][2].geometry.coordinates[0]);
var marker = new google.maps.Marker({
position: latLng,
map: map
});
google.maps.event.addListener(marker, 'click', function(evt) {
infowindow.setContent("name: " + data.rows[0][1] + "<br>desc: " + data.rows[0][0]);
infowindow.open(map, marker);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map {
height: 100%;
width: 100%;
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map"></div>

Creating Markers from my JSON file

I am creating a map with markers from a json file, my issue is that I am unable to get the markers to show on the map. I can link a basic json file, but when I try with an array file I get no markers. My code is:
<script src="js/mapping.js"></script>
<script type="text/javascript">
(function () {
window.onload = function () {
// Creating a new map
var map = new google.maps.Map(document.getElementById("map"), {
center : new google.maps.LatLng(51.50746, -0.127594),
zoom : 8,
mapTypeId : google.maps.MapTypeId.ROADMAP
});
// Creating a global infoBox object that will be reused by all markers
infoBubble = new InfoBubble({
minWidth: 300,
maxWidth: 400,
minHeight: 300,
maxHeight: 400,
arrowSize: 50,
arrowPosition: 50,
arrowStyle: 2,
borderRadius: 0,
shadowStyle: 1,
}); // end Creating a global infoBox object
// Creating a global infoBox object tabs
infoBubble.addTab('Details');
infoBubble.addTab('Info');
// end Creating a global infoBox object tabs
// Custom Markers
var markers = {};
var categoryIcons = {
1 : "images/liver_marker1.png",
2 : "images/liver_marker2.png",
3 : "images/liver_marker3.png",
4 : "images/liver_marker4.png",
5 : "images/liver_marker.png",
6 : "images/liver_marker6.png",
7 : "images/liver_marker.png"
} // end Custom Markers
// Looping through the JSON data
for (var i = 0, length = json.length; i < length; i++) {
var data = json[i],
latLng = new google.maps.LatLng(data.Latitude, data.Longitude);
// Creating a marker and putting it on the map
var marker = new google.maps.Marker({
position : latLng,
map : map,
title : data.title,
icon : categoryIcons[data.category]
});
// Creating a closure to retain the correct data, notice how I pass the current data in the loop into the closure (marker, data)
(function (marker, data) {
// Attaching a click event to the current marker
google.maps.event.addListener(marker, 'click', function(e) {
//infoBubble.setContent('<b>'+data.description+'</b>'+'<br>'+data.name);
infoBubble.updateTab(0, 'Details', data.deviceOwnerName);
infoBubble.updateTab(1, 'Info', data.name);
infoBubble.open(map, marker);
map.panTo(loc);
}); // end Attaching a click event to the current marker
})(marker, data); // end Creating a closure
} // end Looping through the JSON data
}
})();
google.maps.event.addDomListener(window, 'load', initialize);
</script>
And my json array file is:
{
"Device" : [{
"DeviceId" : "e889",
"DeviceRef" : "Te889",
"DeviceName" : null,
"DeviceText" : "Operated by SE",
"DeviceLocation" : {
"Latitude" : "51.484804",
"Longitude" : "-0.103226",
"Address" : {
"SubBuildingName" : null,
"BuildingName" : null,
"BuildingNumber" : null,
"Thoroughfare" : null,
"Street" : "Volcan Road North",
"DoubleDependantLocality" : null,
"DependantLocality" : null,
"PostTown" : "Norwich",
"PostCode" : "NR6 6AQ",
"Country" : "gb"
},
"LocationShortDescription" : null,
"LocationLongDescription" : null
},
"Connector" : [{
"ConnectorId" : "JEV01",
"ConnectorType" : "JEVS G 105 (CHAdeMO)",
"RatedOutputkW" : "50.00",
"RatedOutputVoltage" : null,
"RatedOutputCurrent" : null,
"ChargeMethod" : "DC",
"ChargeMode" : "1",
"ChargePointStatus" : "In service",
"TetheredCable" : "0",
"Information" : null
}
],
"Controller" : {
"OrganisationName" : "SE",
"Website" : null,
"TelephoneNo" : null,
"ContactName" : null
},
"DeviceOwner" : {
"OrganisationName" : "Unknown",
"Website" : null,
"TelephoneNo" : null,
"ContactName" : null
},
"DeviceAccess" : {
"RegularOpenings" : [{
"Days" : "Monday",
"Hours" : {
"From" : "08:00",
"To" : "18:00"
}
}, {
"Days" : "Tuesday",
"Hours" : {
"From" : "08:00",
"To" : "18:00"
}
}, {
"Days" : "Wednesday",
"Hours" : {
"From" : "08:00",
"To" : "18:00"
}
}, {
"Days" : "Thursday",
"Hours" : {
"From" : "08:00",
"To" : "18:00"
}
}, {
"Days" : "Friday",
"Hours" : {
"From" : "08:00",
"To" : "18:00"
}
}, {
"Days" : "Saturday",
"Hours" : {
"From" : "08:30",
"To" : "05:00"
}
}
],
"Open24Hours" : true
},
"PaymentRequiredFlag" : false,
"SubscriptionRequiredFlag" : true,
"Accessible24Hours" : false,
"PhysicalRestrictionFlag" : false,
"PhysicalRestrictionText" : null,
"OnStreetFlag" : false,
"Bearing" : null
}
]}
I am trying to link to the Latitude and Longitude, but I am also looking to display the DeviceId.
Any help would be appreciated.
R
Latitude and Longitude are nested members within your JSON file. You cannot access them without first delving into the DeviceLocation member. I recommend you read this article (http://www.w3schools.com/json/) to understand how JSON works.

Categories

Resources