Filling Google Maps polygon from array of LatLng points - javascript

I have an array of coordinates in LatLng format. I would like to construct a polygon using those coordinates. I know I can hardcode a polygon with individual coordinates like this:
var triangleCoords = [
{lat: A, lng: A},
{lat: B, lng: B},
{lat: C, lng: C}]
Is it possible to place the LatLng data points from my array into triangleCoords and create the polygon that way?

Correct me if I had misunderstood your question.
Q:
Is it possible to place the LatLng data points from my array into triangleCoords and create the polygon that way?
A:
Short answer: No. Unfortunately there is no smartness in the google.maps.Polygon code which would magically try to figure out the lat and lng coordinates of the specified google.maps.LatLng objects for you.
You will need to use the lat() and lng() APIs to return the raw coordinate values from the google.maps.LatLng object and plug that into your array. No shortcut.
Example:
var map = new google.maps.Map(document.getElementById("map"),
{
zoom: 4,
center: new google.maps.LatLng(22.7964, 79.8456),
mapTypeId: google.maps.MapTypeId.HYBRID
});
var coordinateA = new google.maps.LatLng(18.979026,72.949219);
var coordinateB = new google.maps.LatLng(28.613459,77.255859);
var coordinateC = new google.maps.LatLng(22.512557,88.417969);
var coordinateD = new google.maps.LatLng(12.940322,77.607422);
var coords =
[
{lat: coordinateA.lat(), lng: coordinateA.lng() },
{lat: coordinateB.lat(), lng: coordinateB.lng() },
{lat: coordinateC.lat(), lng: coordinateC.lng() },
{lat: coordinateD.lat(), lng: coordinateD.lng() }
];
metros = new google.maps.Polygon(
{
paths: coords,
strokeColor: "#0000FF",
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: "#0000FF",
fillOpacity: 0.26
});
See here for a working JSFiddle example.
http://jsfiddle.net/SamuelToh/3srggbmu/

Here same way am trying polygon google route map dynamically from mysql, it work only on marker, but its not working in polygon ,
here is the code
function initMap()
{
var map = new google.maps.Map(document.getElementById('map'),{
zoom: 5,
center: { lat: 13.36, lng: 77.03 },
});
var planCoordinates = new Array();
// var locations = [
// {lat: 13.367797388285002, lng:77.03707749682616},
// {lat:13.341074247677549, lng:77.0394807561035},
// {lat:13.379153826558369, lng: 77.08685929614256},
// {lat: 13.367797388285002, lng:77.03707749682616},
// ];
<?php
if ($result->num_rows > 0)
{
foreach($result as $key => $row)
{
?>
var locations = [{lat: <?php echo $row['lat']; ?>,lng: <?php echo $row['lng']; ?>}];
for (let i = 0; i < locations.length; i++) {
let obj = locations[i];
planCoordinates[i] = new google.maps.LatLng(obj.lat, obj.lng);
var myLatlng = new google.maps.LatLng(obj.lat, obj.lng);
poly = new google.maps.Polygon({
path: planCoordinates,
geodesic: true,
strokeColor: 'hsla(290,60%,70%,0.3)',
strokeOpacity: 1.0,
strokeWeight: 3,
fillColor: 'hsla(290,60%,70%,0.3)',
fillOpacity: 1.35
});
poly.setMap(map);
var infoWindow = new google.maps.InfoWindow({ content: contentString.this });
var marker = new google.maps.Marker({
position: myLatlng,
title: "Jumbookart",
zIndex: 999,
});
marker.setMap(map);
let ikonica = new google.maps.Marker({
position: myLatlng,
title: "Markeri",
icon: {
path: google.maps.SymbolPath.CIRCLE,
scale: 7
}
});
ikonica.setMap(map);
}
<?php } } ?>
var arrayOfFlightPlans = [locations];
//Loops through all polyline paths and draws each on the map.
for (let i = 0; i < arrayOfFlightPlans.length; i++) {
flightPath = new google.maps.Polygon({
path: arrayOfFlightPlans[i],
geodesic: true,
strokeColor: 'hsla(290,60%,70%,0.3)',
strokeOpacity: 1.0,
strokeWeight: 3,
fillColor: 'hsla(290,60%,70%,0.3)',
fillOpacity: 1.35
});
flightPath.setMap(map);
}
}

Related

How to link a Google Maps Polygon to another website?

I´m creating a map out of polygons to show the different districts of a city. Each polygon (district) should be clickable to another website (a sub-page with information about this area). I already added an add.listener and I can see that there is a link behind a polygon when I hover over the polygon but it is not clickable.
This is what I have so far for one polygon:
<body>
<h1>Headline</h1>
<div id="map"></div>
<script>
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center:{lat:52.516754,lng:13.415202},
mapTypeId: 'terrain'
});
//Define the LatLng coordinates for the polygon's path DistrictOne
var DistrictOneCoords = [
{lat:52.528198300, lng:13.424935300},
{lat:52.527989500, lng:13.423905300},
{lat:52.525065200, lng:13.420386300},
{lat:52.522819700, lng:13.426480300},
{lat:52.521148500, lng:13.429141000},
{lat:52.519111700, lng:13.427596100},
{lat:52.528198300, lng:13.424935300}
];
// Construct the polygon.
var DistrictOne = new google.maps.Polygon({
paths: DistrictOneCoords,
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35
});
DistrictOne.setMap(map);
}
// link
google.maps.event.addListener(DistrictOne, "click", function(event) { window.location.href = "https://www.berlin.de" });
</script>
As I already mentioned I'm not able to click the link.
With the posted code, I get a javascript error:
Uncaught ReferenceError: google is not defined
Your "click" listener is outside of the initMap function, so it is executing before the Google Maps Javascript API v3 has loaded.
Move if inside the initMap function:
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center:{lat:52.516754,lng:13.415202},
mapTypeId: 'terrain'
});
//Define the LatLng coordinates for the polygon's path DistrictOne
var DistrictOneCoords = [
{lat:52.528198300, lng:13.424935300},
{lat:52.527989500, lng:13.423905300},
{lat:52.525065200, lng:13.420386300},
{lat:52.522819700, lng:13.426480300},
{lat:52.521148500, lng:13.429141000},
{lat:52.519111700, lng:13.427596100},
{lat:52.528198300, lng:13.424935300}
];
// Construct the polygon.
var DistrictOne = new google.maps.Polygon({
paths: DistrictOneCoords,
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35
});
DistrictOne.setMap(map);
// link
google.maps.event.addListener(DistrictOne, "click", function(event) {
window.location.href = "https://www.berlin.de"
});
}
proof of concept fiddle
code snippet:
#map {
height: 100%;
}
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
<div id="map"></div>
<script>
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: {
lat: 52.516754,
lng: 13.415202
},
mapTypeId: 'terrain'
});
//Define the LatLng coordinates for the polygon's path DistrictOne
var DistrictOneCoords = [{
lat: 52.528198300,
lng: 13.424935300
},
{
lat: 52.527989500,
lng: 13.423905300
},
{
lat: 52.525065200,
lng: 13.420386300
},
{
lat: 52.522819700,
lng: 13.426480300
},
{
lat: 52.519111700,
lng: 13.427596100
},
{
lat: 52.521148500,
lng: 13.429141000
},
{
lat: 52.528198300,
lng: 13.424935300
}
];
// Construct the polygon.
var DistrictOne = new google.maps.Polygon({
paths: DistrictOneCoords,
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35
});
DistrictOne.setMap(map);
// link
google.maps.event.addListener(DistrictOne, "click", function(event) {
console.log('click, set window.location.href = "https://www.berlin.de"');
// uncomment the line below to make it redirect
// window.location.href = "https://www.berlin.de"
});
}
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?callback=initMap">
</script>
As per your given code. I am implemented polygon in my local.
<script>
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center:{lat:52.516754,lng:13.415202},
mapTypeId: 'terrain'
});
//Define the LatLng coordinates for the polygon's path DistrictOne
var DistrictOneCoords = [
{lat:52.528198300, lng:13.424935300},
{lat:52.527989500, lng:13.423905300},
{lat:52.525065200, lng:13.420386300},
{lat:52.522819700, lng:13.426480300},
{lat:52.521148500, lng:13.429141000},
{lat:52.519111700, lng:13.427596100},
{lat:52.528198300, lng:13.424935300}
];
// Construct the polygon.
var DistrictOne = new google.maps.Polygon({
paths: DistrictOneCoords,
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35
});
DistrictOne.setMap(map);
addEventFunction(DistrictOne);
}
// link
function addEventFunction(DistrictOne) {
google.maps.event.addListener(DistrictOne, "click", function(event) { window.location.href = "https://www.berlin.de" });
}
initMap();

Add marker with label in google map's every end of polyline

I've multiple polylines, I want a marker on every end and start of polyline with a label, I am tracking bike movement, I am getting the polyline but i need to display the time on poly line or on the end point, if i can show the time in the polyline it would be great. I am developing a tracking system, i am getting the lat long, of start and end points i am also abple to draw polylines, i want to display time on the polyline or at least display a marker on every end and show the time... below is my code
var bikearray = [];
$('#searchbtn').on('click', function() {
$.ajax({
url:'http://metrobikes.in/api/a2b-bike-movement-on-map',
method:"GET",
data : {
start_Date : "2017-12-11",
end_date : "2018-01-24",
bike_number : "KA-51-D-6109"
},
}).done(function(data){
bikearray = data.result.data;
initMap();
});
});
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 13,
center: new google.maps.LatLng(12.98966, 77.653637),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var lineSymbol = {
path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW
};
for(i = 0; i < bikearray.length; i++){
var from_lat = parseFloat(bikearray[i].from_lat);
var from_long = parseFloat(bikearray[i].from_long);
var to_lat = parseFloat(bikearray[i].to_lat);
var to_long =parseFloat(bikearray[i].to_long);
var linecolor = bikearray[i].colour;
console.log(bikearray[i].from_lat);
var bikePath = new google.maps.Polyline({
path: [
{lat: from_lat, lng: from_long},
{lat: to_lat, lng: to_long}
],
icons: [{
icon: lineSymbol,
repeat:'35px',
offset: '100%'
}],
geodesic: true,
strokeColor: linecolor,
strokeOpacity: 1.0,
strokeWeight: 2,
map: map
});
bikePath.setMap(map);
}
}
To add a marker to the beginning and end of the polyline, add a marker to the beginning point and to the ending point. To add the time in an InfoWindow on the end marker, add that as well (and trigger a click on it to open it):
for(i = 0; i < bikearray.length; i++){
var from_lat = parseFloat(bikearray[i].from_lat);
var from_long = parseFloat(bikearray[i].from_long);
var startMarker = new google.maps.Marker({
map: map,
position: {lat: from_lat, lng: from_long}
});
var to_lat = parseFloat(bikearray[i].to_lat);
var to_long =parseFloat(bikearray[i].to_long);
var endMarker = new google.maps.Marker({
map: map,
position: {lat: to_lat, lng: to_long}
});
var time = bikearray[i].time;
var infowindow = new google.maps.InfoWindow();
google.maps.event.addListener(endMarker, 'click', (function(marker, time, infowindow) {
return function(evt) {
infowindow.setContent(time);
infowindow.open(map, marker);
}})(endMarker, time, infowindow));
google.maps.event.trigger(endMarker, 'click');
var linecolor = bikearray[i].colour;
proof of concept fiddle
code snippet:
var bikearray = [{
from_lat: 12.98966,
from_long: 77.653637,
to_lat: 12.9715987,
to_long: 77.5945626,
colour: "blue",
time: "12:00"
},
{
from_lat: 13.0826802,
from_long: 80.2707184,
to_lat: 12.9922145,
to_long: 77.7159,
colour: "red",
time: "11:00"
},
]
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 13,
center: new google.maps.LatLng(12.98966, 77.653637),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var lineSymbol = {
path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW
};
for (i = 0; i < bikearray.length; i++) {
var from_lat = parseFloat(bikearray[i].from_lat);
var from_long = parseFloat(bikearray[i].from_long);
var startMarker = new google.maps.Marker({
map: map,
position: {
lat: from_lat,
lng: from_long
}
});
var to_lat = parseFloat(bikearray[i].to_lat);
var to_long = parseFloat(bikearray[i].to_long);
var endMarker = new google.maps.Marker({
map: map,
position: {
lat: to_lat,
lng: to_long
}
});
var time = bikearray[i].time;
var infowindow = new google.maps.InfoWindow();
google.maps.event.addListener(endMarker, 'click', (function(marker, time, infowindow) {
return function(evt) {
infowindow.setContent(time);
infowindow.open(map, marker);
}
})(endMarker, time, infowindow));
google.maps.event.trigger(endMarker, 'click');
var linecolor = bikearray[i].colour;
console.log(bikearray[i].from_lat);
var bikePath = new google.maps.Polyline({
path: [
{
lat: from_lat,
lng: from_long
},
{
lat: to_lat,
lng: to_long
}
],
icons: [{
icon: lineSymbol,
repeat: '35px',
offset: '100%'
}],
geodesic: true,
strokeColor: linecolor,
strokeOpacity: 1.0,
strokeWeight: 2,
map: map
});
bikePath.setMap(map);
}
}
google.maps.event.addDomListener(window, "load", initMap);
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="map"></div>
Looks like this was already answered in Text Within Polyline Google Maps V3
One solution would be using this library from github:
https://github.com/googlemaps/js-map-label
You could use it like this:
var labelPosition = new google.maps.LatLng(middle_lat, middle_long);
var mapLabel = new MapLabel({
text: "Your text",
position: labelPosition ,
map: map,
fontSize: 12
});
You would have to calculate the Middle-Point between the two points.

How to make google Map Api polyline with pin?

I've been created polyline maps like this
but I want set pin in every point...
like this one :
How i can do that?
this is my javascript's code...
<script>
latawal = <?php echo json_encode($locationawal['lat'])?>;
longawal = <?php echo json_encode($locationawal['lon'])?>;
var GoogleMaps = function () {
var mapPolylines = function() {
var map = new GMaps({
div: '#gmap_polylines',
lat: latawal,
lng: longawal,
click: function(e){
console.log(e);
}
});
path = [
<?php foreach ($locationawal10 as $row){ ?>
[<?php echo json_encode($row['lat'])?>, <?php echo json_encode($row['lon'])?>],
<?php } ?>
];
map.drawPolyline({
path: path,
strokeColor: 'Red',
strokeOpacity: 0.6,
strokeWeight: 4
});
}
return {
//main function to initiate map samples
init: function () {
mapPolylines();
}
};
}();
</script>
Thanks before.... I hope someone can help me about this... sorry for my bad english..
It seems you need to make multiple markers. You will be using the latlang values from your latawal and longawal json files for each marker as LatLng values for the markers. Check this SO thread for additional reference.
I did a quick demo for you to convey the idea. You may need to modify parts which needs cleaner coding. This is the relevant part:
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 3,
center: {lat: 0, lng: -180},
mapTypeId: google.maps.MapTypeId.TERRAIN
});
var flightPlanCoordinates = [
{lat: -32.342841, lng: 119.882813},
{lat: -32.194209, lng: 144.492188},
{lat: -19.248922, lng: 145.546875},
{lat: -18.916680, lng: 124.804688}
];
var markerCoordinates = [
[-32.342841, 119.882813],
[-32.194209, 144.492188],
[-19.248922, 145.546875],
[-18.916680, 124.804688]
];
var marker, i;
for (i = 0; i < markerCoordinates.length; i++) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(markerCoordinates[i][i-i], markerCoordinates[i][1]),
map: map,
title: 'Hello World!'
});
}
var flightPath = new google.maps.Polyline({
path: flightPlanCoordinates,
geodesic: true,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 2
});
flightPath.setMap(map);
}
This is what it looks like:
It would defintely help if you read the docs about Markers too.
Simplest solution is to process the path and add markers at each vertex.
for (var i=0; i<path.length; i++) {
map.addMarker({
lat: path[i].lat,
lng: path[i].lng,
})
}
proof of concept fiddle
code snippet:
function initialize() {
latawal = 41.5;
longawal = -72.4;
var GoogleMaps = function() {
var mapPolylines = function() {
var map = new GMaps({
div: '#gmap_polylines',
lat: latawal,
lng: longawal,
zoom: 8,
click: function(e) {
console.log(e);
}
});
path = [{
lat: 42,
lng: -72
}, {
lat: 41,
lng: -72.4
}, {
lat: 41.5,
lng: -72.6
}];
map.drawPolyline({
path: path,
strokeColor: 'Red',
strokeOpacity: 0.6,
strokeWeight: 4
});
for (var i = 0; i < path.length; i++) {
map.addMarker({
lat: path[i].lat,
lng: path[i].lng,
})
}
}
return {
//main function to initiate map samples
init: function() {
mapPolylines();
}
};
}();
GoogleMaps.init();
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#gmap_polylines {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gmaps.js/0.4.12/gmaps.min.js"></script>
<div id="gmap_polylines"></div>

Google map circle with label

I created map view using google map api, changed markers into circles by using google.maps.Circle circles printing on map with no issues on that but I can't add label or text into it. How can I fix that.
Here is the code I used to print circles
function initialize() {
var frrlanser_marker = {
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35,
radius: 60 * 100
};
var latlng = new google.maps.LatLng(6.951974, 80.720160);
var myOptions = {
scrollwheel: false,
zoom: 10,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map"),
myOptions);
<?php foreach($results as $val): ?>
<?php if($val->geo_location != ""): ?>
<?php if($val->fontUserTypeId == 1) { ?>
var fill_color_val = '#3888ff';
<?php } else { ?>
var fill_color_val = '#70d04f';
<?php } ?>
<?php $LatLng = explode(",", $val->geo_location); ?>
var latitude = <?php echo $LatLng[0]; ?>;
var lontitude = <?php echo $LatLng[1]; ?>;
var myLatLng = {lat: latitude, lng: lontitude};
var marker = new google.maps.Marker({
position: myLatLng,
map: map
});
// Add circle overlay and bind to marker
var circle = new google.maps.Circle({
map: map,
radius: 3200, // 10 miles in metres
fillColor: fill_color_val,
strokeColor: '#FFFFFF',
strokeWeight: 2,
fillOpacity: 1,
});
circle.bindTo('center', marker, 'position');
marker.setVisible(false);
}
google.maps.event.addDomListener(window, "load", initialize);
You can add an InfoBox with your desired label/text over the circle.
proof of concept fiddle
code snippet:
function initialize() {
var frrlanser_marker = {
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35,
radius: 60 * 100
};
var latlng = new google.maps.LatLng(6.951974, 80.720160);
var myOptions = {
scrollwheel: false,
zoom: 10,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map"),
myOptions);
var fill_color_val = '#3888ff';
var latitude = 6.951974;
var lontitude = 80.720160;
var myLatLng = google.maps.LatLng(latitude, lontitude);
var marker = new google.maps.Marker({
position: latlng,
map: map
});
// Add circle overlay and bind to marker
var circle = new google.maps.Circle({
map: map,
radius: 3200, // 10 miles in metres
fillColor: fill_color_val,
strokeColor: '#FFFFFF',
strokeWeight: 2,
fillOpacity: 1,
});
circle.bindTo('center', marker, 'position');
marker.setVisible(false);
var labelText = "1";
var myOptions = {
content: labelText,
boxStyle: {
border: "none",
textAlign: "center",
fontSize: "10pt",
width: "50px"
},
disableAutoPan: true,
pixelOffset: new google.maps.Size(-25, -5),
position: latlng,
closeBoxURL: "",
isHidden: false,
pane: "floatPane",
enableEventPropagation: true
};
var ibLabel = new InfoBox(myOptions);
ibLabel.open(map);
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<script src="https://cdn.jsdelivr.net/npm/google-maps-infobox#2.0.0/infobox-module.min.js"></script>
<div id="map"></div>

How to change the path of a Polyline in Maps API v3?

There is a way to change the position of a polyline with the Google Maps API v3 in Javascript ?
A way to change the "path" option for a line already drawn ? I already changed the position of the "Circle" but not "RadiusLine"...
Map init code :
var latlng = new google.maps.LatLng(lat, lng);
var map = new google.maps.Map(document.getElementById('map'),{
zoom: 13,
center: latlng,
mapTypeId: google.maps.MapTypeId.HYBRID,
streetViewControl: false
});
var marker = new google.maps.Marker({
position: latlng,
map: map
});
var sunCircle = {
strokeColor: "#c3fc49",
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: "orange",
fillOpacity: 0.15,
map: map,
center: latlng,
radius: 1500
};
var origin = sunCircle.center;
var endpoint = google.maps.geometry.spherical.computeOffset(sunCircle.center,sunCircle.radius,180+sunPos);
var radiusLineSettings = {
clickable: false,
map: map,
strokeColor: "orange",
strokeWeight: 10,
path: [origin,endpoint]
};
Circle = new google.maps.Circle(sunCircle);
RadiusLine = new google.maps.Polyline(radiusLineSettings);
The solution :
RadiusLine.setPath(...)

Categories