google maps loadGeoJson change marker icon on click - javascript

I am loading the markers from a json file with loadGeoJson.
I can SET the marker icon/img on load, but I don't know how to CHANGE it on click.
how to target the clicked marker and do a setIcon or similar?
javascript:
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 6,
center: new google.maps.LatLng(2.8,-187.3),
mapTypeId: 'terrain'
});
map.data.loadGeoJson('geoJson2.json');
map.data.setStyle(function(feature) {
return {icon:feature.getProperty('icon')};
});
map.data.addListener("click", event => {
console.log(event.feature.getProperty("hicon"));
//CHANGE MARKER ICON -> event.feature.getProperty("hicon")
});
}
json:
{
"type":"FeatureCollection",
"features":[
{
"type":"Feature",
"properties":{
"name":"nameOne",
"icon":"marker1.png",
"hicon":"marker1HOVER.png",
"id":1
},
"geometry":{
"type":"Point",
"coordinates":[
-59.58984374999999,
-37.97884504049711
]
}
}
]
}

See the example of dynamic styling in the documentation.
map.data.setStyle(function(feature) {
var icon=feature.getProperty('icon');
if (feature.getProperty("isHighlighted"))
icon=feature.getProperty('hicon');
return {
icon: icon
};
});
map.data.addListener("click", event => {
if (!event.feature.getProperty("isHighlighted"))
event.feature.setProperty("isHighlighted", true);
else
event.feature.setProperty("isHighlighted", false);
console.log(event.feature.getProperty("hicon"));
//CHANGE MARKER ICON -> event.feature.getProperty("hicon")
});
proof of concept fiddle
code snippet:
"use strict";
let map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 6,
center: new google.maps.LatLng(-37.9788, -59.58984375),
mapTypeId: 'terrain'
});
map.data.addGeoJson(geoJson);
map.data.setStyle(function(feature) {
var icon = feature.getProperty('icon');
if (feature.getProperty("isHighlighted"))
icon = feature.getProperty('hicon');
return {
icon: icon
};
});
map.data.addListener("click", event => {
if (!event.feature.getProperty("isHighlighted"))
event.feature.setProperty("isHighlighted", true);
else
event.feature.setProperty("isHighlighted", false);
console.log(event.feature.getProperty("hicon"));
//CHANGE MARKER ICON -> event.feature.getProperty("hicon")
});
}
var geoJson = {
"type": "FeatureCollection",
"features": [{
"type": "Feature",
"properties": {
"name": "nameOne",
"icon": "https://maps.google.com/mapfiles/ms/micons/blue.png",
"hicon": "https://maps.google.com/mapfiles/ms/micons/yellow.png",
"id": 1
},
"geometry": {
"type": "Point",
"coordinates": [-59.58984374999999, -37.97884504049711]
}
}]
};
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
<!DOCTYPE html>
<html>
<head>
<title>Data Layer: Styling</title>
<script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap&libraries=&v=weekly" defer></script>
<!-- jsFiddle will insert css and js -->
</head>
<body>
<div id="map"></div>
</body>
</html>

Related

Functionally setting Leaflet marker colors by a property for geojson data

Similarly to this question, we want to functionally set our Leaflet map's marker's colors based off a value, except our map is built with geojson data.
We want markers' colors to be functional to color_value (eg. different shade of green), but we don't know how to build that like this answer explains with L.AwesomeMarkers.icon({markerColor: determineColor(rating)});, because the markers for all our entries are built at once with pointToLayer: function (feature, coordinates) {return L.marker(coordinates, { icon: customicon });}. Simplified eg:
<!DOCTYPE html>
<style>
html,
body { margin: 0px; height: 100%; }
body {display: flex;}
</style>
<body>
<link rel="stylesheet" href="https://unpkg.com/leaflet#1.7.1/dist/leaflet.css"
integrity="sha512-xodZBNTC5n17Xt2atTPuE1HxjVMSvLVW9ocqUKLsCC5CXdbqCmblAshOMAS6/keqq/sMZMZ19scR4PsZChSR7A=="
crossorigin="" />
<script src="https://unpkg.com/leaflet#1.7.1/dist/leaflet.js"
integrity="sha512-XQoYMqMTK8LvdxXYG3nZ448hOEQiglfqkJs1NOQV44cWnUrBc8PkAOcXy20w0vlaXaVUearIOBhiXZ5V3ynxwA=="
crossorigin=""></script>
<div id="mapid" style="flex: 1"></div>
<script>var myMap = L.map("mapid");
L.tileLayer('https://{s}.tile.openstreetmap.fr/hot/{z}/{x}/{y}.png').addTo(myMap);
myMap.setView([51.5, -0.09], 10);
var geojsonFeatureCollection =
{
"type": "FeatureCollection",
"features": [{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [-0.09, 51.5]
},
"properties": {
"color_value": 1
}
},
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [-0.4, 51.5]
},
"properties": {
"color_value": 10
}
}]
}
const myCustomColor = '#007a83'
const markerHtmlStyles = `
background-color: ${myCustomColor}; width: 1.3rem; height: 1.3rem; display: block;`
const customicon = L.divIcon({html: `<span style="${markerHtmlStyles}" />`})
L.geoJSON(geojsonFeatureCollection, {
pointToLayer: function (feature, coordinates) {
return L.marker(coordinates, { icon: customicon });
}
})
.addTo(myMap);
</script>
</body>
</html>
We've found this tutorial which gets us a little closer by explaining how to choose different markers based off some value, but we want to set the color itself, not choose from existing markers.
How can we make myCustomColor functional to color_value, or otherwise set marker colors programmatically for geojson data?
You are almost there! :-)
You can define the desired color directly as a property on each GeoJSON feature. Leaflet passes each feature of the GeoJSON collection to pointToLayer, allowing you to access its properties.
Check out the snippet below.
var myMap = L.map("mapid");
L.tileLayer('https://{s}.tile.openstreetmap.fr/hot/{z}/{x}/{y}.png').addTo(myMap);
myMap.setView([51.5, -0.09], 10);
var geojsonFeatureCollection = {
"type": "FeatureCollection",
"features": [{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [-0.09, 51.5]
},
"properties": {
// You can define a different color for each property
// and access it in pointToLayer().
"color_value": '#007a83'
}
},
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [-0.4, 51.5]
},
"properties": {
// Here I might use a different color
"color_value": '#003134'
}
}
]
};
L.geoJSON(geojsonFeatureCollection, {
pointToLayer: function(feature, coordinates) {
// Leaflet passes each GeoJSON feature in the collection in here,
// allowing you to access the feature's properties
const color_value = feature.properties.color_value;
// With the color obtained from the properties, you can now create
// the marker icon with the correct color.
const markerHtmlStyles = `background-color: ${color_value}; width: 1.3rem; height: 1.3rem; display: block;`;
const customicon = L.divIcon({
html: `<span style="${markerHtmlStyles}" />`
});
return L.marker(coordinates, {
icon: customicon
});
},
})
.addTo(myMap);
html,
body {
margin: 0px;
height: 100%;
}
body {
display: flex;
}
<!DOCTYPE html>
<body>
<link rel="stylesheet" href="https://unpkg.com/leaflet#1.7.1/dist/leaflet.css" integrity="sha512-xodZBNTC5n17Xt2atTPuE1HxjVMSvLVW9ocqUKLsCC5CXdbqCmblAshOMAS6/keqq/sMZMZ19scR4PsZChSR7A==" crossorigin="" />
<script src="https://unpkg.com/leaflet#1.7.1/dist/leaflet.js" integrity="sha512-XQoYMqMTK8LvdxXYG3nZ448hOEQiglfqkJs1NOQV44cWnUrBc8PkAOcXy20w0vlaXaVUearIOBhiXZ5V3ynxwA==" crossorigin=""></script>
<div id="mapid" style="flex: 1"></div>
</body>
</html>
Alternatively, if you want to calculate the color based off color_value, you can proceed almost the same way: Read color_value property inside pointToLayer, generate the color (e.g., by using an approach like the one outlined here: Programmatically Lighten or Darken a hex color (or rgb, and blend colors)) and pass it to your marker's styling.
Hope this helps!

Is there a way to open a popup input text after a polygon is created in leaflet?

I'm trying to make a web app that uses leaflet to display a map, users should be able to draw and edit polygons over the map and they should have the ability to name each polygon they create.
I want to open a popup when a polygon is created that asks for a name and then set it to a property in a geojson feature.
I tried to follow this example Leaflet popup form but I couldn't get it to work with the leaflet draw created event.
Here's what I got.
// Map center
var center = [-32.692825, -62.104689];
// Map creation
var map = L.map('map').setView(center, 14);
// Map tile layer
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
maxZoom: 19,
attribution: '© OpenStreetMap contributors'
}).addTo(map);
// Initialise the FeatureGroup to store editable layers
var editableLayers = new L.FeatureGroup();
map.addLayer(editableLayers);
// Draw plugin options
var drawPluginOptions = {
position: 'topleft',
draw: {
polygon: {
allowIntersection: false, // Restricts shapes to simple polygons
drawError: {
color: '#e1e100', // Color the shape will turn when intersects
message: '<strong>Oh snap!<strong> you can\'t draw that!' // Message that will show when intersect
},
shapeOptions: {
color: '#97009c'
}
},
// disable toolbar item by setting it to false
polyline: false,
circle: false, // Turns off this drawing tool
rectangle: false,
marker: false,
},
edit: {
featureGroup: editableLayers,
polygon: {
allowIntersection: false
} //REQUIRED!!
}
};
// Initialise the draw control and pass it the FeatureGroup of editable layers
var drawControl = new L.Control.Draw(drawPluginOptions);
map.addControl(drawControl);
var editableLayers = new L.FeatureGroup();
map.addLayer(editableLayers);
// draw created event handler
function polygonCreateHandler(e) {
var type = e.layerType;
var layer = e.layer;
if (type != 'polygon') {
alert("ESTO NO ES UN POLIGONO");
return;
}
editableLayers.addLayer(layer);
}
// draw created event
map.on('draw:created', function(e) {
polygonCreateHandler(e);
});
//Ignore this
/*jshint multistr: true */
var template = '<form id="popup-form">\
<label for="input-speed">New speed:</label>\
<input id="input-speed" class="popup-input" type="number" />\
<button id="button-submit" type="button">Save Changes</button>\
</form>';
/*
** fetch geojson example
let geojson_url = "https://raw.githubusercontent.com/delineas/leaflet-flyto-webpack-bulma/master/src/data/arboles_singulares_en_espacios_naturales.geojson"
fetch(
geojson_url
).then(
res => res.json()
).then(
data => {
let geojsonlayer = L.geoJson(data, {
onEachFeature: function(feature, layer) {
layer.bindPopup(feature.properties['arbol_nombre'])
layer.setIcon(treeMarker)
}
}).addTo(map)
map.fitBounds(geojsonlayer.getBounds())
}
)
** layer polygon example
var geojson_msjz_polygon = {
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"properties": { "name": "Test Distrito electoral"},
"geometry": {
"type": "Polygon",
"coordinates": [
[
[
-62.103266716003425,
-32.687209099455636
],
[
-62.13047504425048,
-32.68211618935444
],
[
-62.133564949035645,
-32.693746380985395
],
[
-62.106142044067376,
-32.698838627713116
],
[
-62.103266716003425,
-32.687209099455636
]
]
]
}
}
]
};
let geojsonlayer = L.geoJson(geojson_msjz_polygon, {
onEachFeature: function(feature, layer) {
let text = L.tooltip({
permanent: true,
direction: 'center',
className: 'text'
})
.setContent(feature.properties.name)
.setLatLng(layer.getBounds().getCenter());
text.addTo(map);
}
}).addTo(map);
map.fitBounds(geojsonlayer.getBounds())
*/
#map {
height: 98vh;
width: 100hw;
}
body {
margin: 0;
}
html,
body,
#leaflet {
height: 100%;
}
.popup-table {
width: 100%;
}
.popup-table-row {
background-color: grey;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.0.0-beta.2.rc.2/leaflet.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.0.0-beta.2.rc.2/leaflet.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet.draw/0.2.3/leaflet.draw.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/leaflet.draw/0.2.3/leaflet.draw.css" rel="stylesheet" />
<div id="map"></div>
Just bind a popup on the created layer and open it once it is created
function polygonCreateHandler(e) {
var type = e.layerType;
var layer = e.layer;
if (type != 'polygon') {
alert("ESTO NO ES UN POLIGONO");
return;
}
editableLayers.addLayer(layer);
layer.bindPopup(template).openPopup(); // here create and open the popup with your form
}
// Map center
var center = [-32.692825, -62.104689];
// Map creation
var map = L.map('map').setView(center, 14);
// Map tile layer
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
maxZoom: 19,
attribution: '© OpenStreetMap contributors'
}).addTo(map);
// Initialise the FeatureGroup to store editable layers
var editableLayers = new L.FeatureGroup();
map.addLayer(editableLayers);
// Draw plugin options
var drawPluginOptions = {
position: 'topleft',
draw: {
polygon: {
allowIntersection: false, // Restricts shapes to simple polygons
drawError: {
color: '#e1e100', // Color the shape will turn when intersects
message: '<strong>Oh snap!<strong> you can\'t draw that!' // Message that will show when intersect
},
shapeOptions: {
color: '#97009c'
}
},
// disable toolbar item by setting it to false
polyline: false,
circle: false, // Turns off this drawing tool
rectangle: false,
marker: false,
},
edit: {
featureGroup: editableLayers,
polygon: {
allowIntersection: false
} //REQUIRED!!
}
};
// Initialise the draw control and pass it the FeatureGroup of editable layers
var drawControl = new L.Control.Draw(drawPluginOptions);
map.addControl(drawControl);
var editableLayers = new L.FeatureGroup();
map.addLayer(editableLayers);
var template = '<form id="popup-form">\
<label for="input-speed">New speed:</label>\
<input id="input-speed" class="popup-input" type="number" />\
<button id="button-submit" type="button">Save Changes</button>\
</form>';
var createdPolygonTemplate = '<form id="popup-form">\
<label for="input-speed">Name:</label>\
<input id="name" type="text" />\
</form>';
// draw created event handler
function polygonCreateHandler(e) {
var type = e.layerType;
var layer = e.layer;
if (type != 'polygon') {
alert("ESTO NO ES UN POLIGONO");
return;
}
editableLayers.addLayer(layer);
layer.bindPopup(createdPolygonTemplate).openPopup()
}
// draw created event
map.on('draw:created', function(e) {
polygonCreateHandler(e);
});
//Ignore this
/*jshint multistr: true */
/*
** fetch geojson example
let geojson_url = "https://raw.githubusercontent.com/delineas/leaflet-flyto-webpack-bulma/master/src/data/arboles_singulares_en_espacios_naturales.geojson"
fetch(
geojson_url
).then(
res => res.json()
).then(
data => {
let geojsonlayer = L.geoJson(data, {
onEachFeature: function(feature, layer) {
layer.bindPopup(feature.properties['arbol_nombre'])
layer.setIcon(treeMarker)
}
}).addTo(map)
map.fitBounds(geojsonlayer.getBounds())
}
)
** layer polygon example
var geojson_msjz_polygon = {
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"properties": { "name": "Test Distrito electoral"},
"geometry": {
"type": "Polygon",
"coordinates": [
[
[
-62.103266716003425,
-32.687209099455636
],
[
-62.13047504425048,
-32.68211618935444
],
[
-62.133564949035645,
-32.693746380985395
],
[
-62.106142044067376,
-32.698838627713116
],
[
-62.103266716003425,
-32.687209099455636
]
]
]
}
}
]
};
let geojsonlayer = L.geoJson(geojson_msjz_polygon, {
onEachFeature: function(feature, layer) {
let text = L.tooltip({
permanent: true,
direction: 'center',
className: 'text'
})
.setContent(feature.properties.name)
.setLatLng(layer.getBounds().getCenter());
text.addTo(map);
}
}).addTo(map);
map.fitBounds(geojsonlayer.getBounds())
*/
#map {
height: 98vh;
width: 100hw;
}
body {
margin: 0;
}
html,
body,
#leaflet {
height: 100%;
}
.popup-table {
width: 100%;
}
.popup-table-row {
background-color: grey;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.0.0-beta.2.rc.2/leaflet.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.0.0-beta.2.rc.2/leaflet.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet.draw/0.2.3/leaflet.draw.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/leaflet.draw/0.2.3/leaflet.draw.css" rel="stylesheet" />
<div id="map"></div>
Yes, the next is a code example:
<div id="map" style="width: 100%; height: 500px;"></div>
<script>
var map = L.map('map', {
center: [18.9, -71.2],
zoom: 8,
});
const tileURL = 'https://cartodb-basemaps-{s}.global.ssl.fastly.net/light_all/{z}/{x}/{y}.png'
L.tileLayer(tileURL).addTo(map);
drawnItems = L.featureGroup().addTo(map);
var drawControl = new L.Control.Draw({
edit: {
featureGroup: drawnItems,
},
});
var getName = function(layer) {
var name = prompt('please, enter the geometry name', 'geometry name');
return name;
};
map.addControl(drawControl);
map.on(L.Draw.Event.CREATED, function(e) {
var layer = e.layer;
var name = getName(layer);
if (name == 'geometry name') {
layer.bindPopup('-- no name provided --');
} else if (name == '') {
layer.bindPopup('-- no name provided --');
} else {
layer.bindTooltip(name, {permanent:true, direction:'top'})
};
drawnItems.addLayer(layer);
});
</script>
And this is the result:
enter image description here
Do not forget the cdn's:
<link rel="stylesheet" href="https://unpkg.com/leaflet#1.7.1/dist/leaflet.css" />
<script src="https://unpkg.com/leaflet#1.7.1/dist/leaflet.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet.draw/1.0.4/leaflet.draw-src.css" integrity="sha512-vJfMKRRm4c4UupyPwGUZI8U651mSzbmmPgR3sdE3LcwBPsdGeARvUM5EcSTg34DK8YIRiIo+oJwNfZPMKEQyug==" crossorigin="anonymous" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet.draw/1.0.4/leaflet.draw.js" integrity="sha512-ozq8xQKq6urvuU6jNgkfqAmT7jKN2XumbrX1JiB3TnF7tI48DPI4Gy1GXKD/V3EExgAs1V+pRO7vwtS1LHg0Gw==" crossorigin="anonymous"></script>

using Google Map Javascript API to render a GeoJSON Polygon overlay from JavaScript Variable

I am trying to render a GeoJSON polygon from a variable called data using the Google Javascript API. The overlay does not render properly and I do not know why. Can somebody please show me how to render a polygon on the map?
<!DOCTYPE html>
<html>
<head>
<script src="http://maps.googleapis.com/maps/api/js"></script>
<script>
var x=new google.maps.LatLng(40.75597,-73.974228);
function initialize() {
var data = { "type" : "Polygon", "coordinates" : [ [ [ -73.974228, 40.75597 ], [ -73.983841, 40.742931 ], [ -74.008133, 40.75307500000001 ], [ -73.998131, 40.765915 ], [ -73.974228, 40.75597 ] ] ] }
var mapProp = {
center:x,
zoom:4,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map=new google.maps.Map(document.getElementById("googleMap"),mapProp);
map.data.loadGeoJson(data);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="googleMap" style="width:500px;height:380px;"></div>
</body>
</html>
I get a javascript error with your code: Uncaught InvalidValueError: not a Feature or FeatureCollection. Make your polygon a "Feature":
var data = {
type: "Feature",
geometry: {
"type": "Polygon",
"coordinates": [
[
[-73.974228, 40.75597],
[-73.983841, 40.742931],
[-74.008133, 40.75307500000001],
[-73.998131, 40.765915],
[-73.974228, 40.75597]
]
]
}
};
working fiddle
code snippet:
function initialize() {
var data = {
type: "Feature",
geometry: {
"type": "Polygon",
"coordinates": [
[
[-73.974228, 40.75597],
[-73.983841, 40.742931],
[-74.008133, 40.75307500000001],
[-73.998131, 40.765915],
[-73.974228, 40.75597]
]
]
}
};
var mapProp = {
center: new google.maps.LatLng(40.75597, -73.974228),
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("googleMap"), mapProp);
map.data.addGeoJson(data);
}
google.maps.event.addDomListener(window, 'load', initialize);
html, body, #googleMap {
width: 100%;
height: 100%;
}
<script src="https://maps.google.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="googleMap"></div>
Firstly, geojson object must be a Feature or FeatureCollection.
Secondly, use:
map.data.addGeoJson(data) to load geojson from variable
instead of:
map.data.loadGeoJson(data) for loading geojson from .json files
More info in Google Maps API

Notice: Array to string conversion error when converting array from php to javascript

I'm trying to get an array of latitudes and longitudes from the php arrays $lat and $long which are being retrieved by a database.
<?php
...
$lat[$latlongindex] = $results_row['latitude'];
$long[$latlongindex] = $results_row['longitude'];
echo "
<script type=\"text/javascript\">
var locations = $latlongindex;
var jslat = <?php echo json_encode($lat); ?>;
var jslong = <?php echo json_encode($long); ?>; // <----------Line 58
var map = new GMaps({
div: '#map',
lat: 39.833,
lng: -98.583,
width: '900px',
height: '500px',
zoom: 4,
zoomControl : true,
zoomControlOpt: {
style : 'SMALL',
position: 'TOP_LEFT'
},
panControl : false,
});
//------------------------------------------------ADD MARKERS--------------
for (var i = 0; i<locations; i++) {
map.addMarker({
position: new google.maps.LatLng( jslat[i], jslong[i] ),
});
}
</script>
"; // <--------------------------------Line 83
}
}
?>
Just as a quick check I can echo json_encode($lat) and json_encode($long) and they are displayed correctly but when I try use them inside the javascript I get "Notice: Array to string conversion" in lines 58 and 83. If I explicitly state the location like:
var jslat = [];
jslat[0] = $lat[0];
It will run correctly but obviously just shows the first marker. Thus I know I can access the elements of the $lat and $long arrays. I feel like this is a simplistic error but can't seem to find anything on stack that is a similar issue.
Any help would be great. Thanks.
// MAP CODE
$qry_country_map = 'Select name, refugee, lat, lng FROM '.$table_name.' WHERE 1 AND status = 1';
$country_data_map = $wpdb->get_results($qry_country_map , ARRAY_A);
//echo "<pre>";print_r($country_data_map);exit;
$array_string = "[";
for($m=0;$m<count($country_data_map);$m++) {
$array_string .= "['".$country_data_map[$m]['name']."', '".$country_data_map[$m]['name']."','".$country_data_map[$m]['refugee']."','".$country_data_map[$m]['lat']."', '".$country_data_map[$m]['lng']."'],";
}
$array_string = substr($array_string, 0,-1);
$array_string .= "]";
?>
<style>
#map{
height: 400px;
}
a[href^="http://maps.google.com/maps"]{display:none !important}
.gmnoprint a, .gmnoprint span {
display:none;
}
.gmnoprint div {
background:none !important;
}
</style>
<script src="http://maps.google.com/maps/api/js?sensor=false"></script>
<div id="map"></div>
<script type="text/javascript">
var marker_image = '<?php echo $plugin_image_url;?>';
// Define your locations: HTML content for the info window, latitude, longitude
var locations = <?php echo $array_string;?>;
var map = new google.maps.Map(document.getElementById('map'), {
center: new google.maps.LatLng(26.3351, 17.2283),
mapTypeControl: false,
scaleControl: false,
streetViewControl: false,
overviewMapControl: false,
panControl: false,
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.SMALL
},
zoom: 2,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var styles = [
{
featureType: "landscape",
stylers: [
{ visibility: "on" },
{ color: "#FFFFFF"}
]
},
{
featureType: "water",
stylers: [
{ visibility: "on" },
{ color: "#CCCCCC"}
]
},
{
featureType: "administrative",
elementType: "geometry.fill",
stylers: [
{ visibility: "off" }
]
},
{
featureType: "all",
elementType: "labels",
stylers: [
{ visibility: "off" }
]
}
];
map.setOptions({styles: styles});
var infowindow = new google.maps.InfoWindow({
maxWidth: 160
});
var marker;
var markers = new Array();
// Add the markers and infowindows to the map
for (var i = 0; i < locations.length; i++)
{
if(locations[i][3]!='' && locations[i][4]!='' && locations[i][2]!='')
{
var scale;
if(locations[i][2]<100)
scale = locations[i][2];
else if(locations[i][2]>100 && locations[i][2]<500)
scale = locations[i][2]/25;
else if(locations[i][2]>500 && locations[i][2]<1000)
scale = locations[i][2]/60;
else if(locations[i][2]>1000 && locations[i][2]<10000)
scale = locations[i][2]/275;
else if(locations[i][2]>10000 && locations[i][2]<100000)
scale = locations[i][2]/1600;
else if(locations[i][2]>100000 && locations[i][2]<500000)
scale = locations[i][2]/7500;
else if(locations[i][2]>500000 && locations[i][2]<1000000)
scale = locations[i][2]/10500;
scale = Math.round(scale);
if(scale!=0)
{
//console.log(scale);
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][3], locations[i][4]),
map: map,
icon: {
url: marker_image,
scaledSize: new google.maps.Size(scale, scale),
size:new google.maps.Size(scale, scale)
}
});
//ADD EVENT TO SHOW INFOWINDOW
google.maps.event.addListener(marker, 'mouseover', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
//marker.setIcon(new google.maps.MarkerImage('http://192.168.5.33/map-marker-hover.png'));
//marker.icon.scaledSize = new google.maps.Size(scale,scale);
//marker.icon.size = new google.maps.Size(scale,scale);
}
})(marker, i));
//ADD EVENT TO HIDE INFOWINDOW
google.maps.event.addListener(marker, 'mouseout', (function(marker, i) {
return function() {
infowindow.close(map, marker);
//marker.setIcon(new google.maps.MarkerImage('http://192.168.5.33/map-marker.png'));
//marker.icon.scaledSize = new google.maps.Size(scale,scale);
//marker.icon.size = new google.maps.Size(scale,scale);
}
})(marker, i));
}
}
}
</script>
See the variable named $array_string i have created it in php and then just echo in js to make a js array and then i have looped with the lat and long to display markers.
i have coded some things for the custom marker image and marker size scaling according to value and effect on mouseover and mouseout.
You just need to copy paste this code make minute changes and you are done.
Let me know if something goes wrong :)

GeoJSON Point name & description not displayed when using Google Map API V3

I am starting to use the Google Map Javascript API V3 and wish to display markers on a map, using GeoJSON. My GeoJSON is as follows:
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [153.236112, -27.779627]
},
"properties": {
"name": "[153.236112, -27.779627]",
"description": "Timestamp: 16:37:16.293"
}
},
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [153.230447, -27.777501]
},
"properties": {
"name": "[153.230447, -27.777501]",
"description": "Timestamp: 16:37:26.298"
}
}
]
}
And my JavaScript code to load the GeoJSON:
var map;
var marker;
function initialize() {
// Create a simple map.
map = new google.maps.Map(document.getElementById('map-canvas'), {
zoom: 14,
center: ${lastPosition}
});
// Load the associated GeoJSON
var url = 'fieldDataGeoJSON';
url += '?deviceId=' + deviceId + '&fieldId=' + fieldId;
map.data.loadGeoJson(url);
}
google.maps.event.addDomListener(window, 'load', initialize);
Note: the URL "fieldDataGeoJSON.." returns the GeoJSON, as you might have already figured out.
This works well: the markers are shown on the map, at the good location. But the fields "name" and "description" present in the GeoJSON are not linked to the markers, meaning that they are not displayed when I click on the marker.
I guess that the first question would be: "Is it supposed to be supported?". If not, does it mean that I have to parse the GeoJSON to add the names and descriptions? Do you have any hints on how to achieve this?
Thank you in advance for your help!
Normal Google Maps Javascript API v3 event listeners work, as do normal infowindows.
var map;
var infowindow = new google.maps.InfoWindow();
function initialize() {
// Create a simple map.
map = new google.maps.Map(document.getElementById('map-canvas'), {
zoom: 14,
center: new google.maps.LatLng(-27.779627,153.236112)
});
google.maps.event.addListener(map, 'click', function() {
infowindow.close();
});
// Load the associated GeoJSON
var url = 'http://www.geocodezip.com/fieldDataGeoJSON.txt';
map.data.loadGeoJson(url);
// Set event listener for each feature.
map.data.addListener('click', function(event) {
infowindow.setContent(event.feature.getProperty('name')+"<br>"+event.feature.getProperty('description'));
infowindow.setPosition(event.latLng);
infowindow.setOptions({pixelOffset: new google.maps.Size(0,-34)});
infowindow.open(map);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
working example

Categories