I am using cartodb(google map) to draw polylines and then inserting a polygon in google maps.
The problem is, two maps load, on top of each other. One with the cartodb polylines and one with the polygon. I need them to be on the same map. Not sure what I am doing wrong.
function main() {
var map;
var sql; // sql query object for querying CartoDB SQL API
var sublayers = [];
// create google maps map
var mapOptions = {
zoom: 12,
center: new google.maps.LatLng(26.178347,50.6116694),
mapTypeId: google.maps.MapTypeId.HYBRID,
panControl: true,
panControlOptions: {
position: google.maps.ControlPosition.TOP_RIGHT
},
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.LARGE,
position: google.maps.ControlPosition.TOP_RIGHT
},
};
map = new google.maps.Map(document.getElementById('map'), mapOptions);
// create layer and add to the map, then add some interactive elements
cartodb.createLayer(map, 'http://zbahrain.cartodb.com/api/v2/viz/f5073bec-b841-11e4-b79c-0e4fddd5de28/viz.json')
.addTo(map)
.on('done', function(layer) {
var subLayerOptions = {
sql: "SELECT * FROM roadscomplete where block = '525'"}
var sublayer = layer.getSubLayer(0);
sublayer.set(subLayerOptions);
sublayers.push(sublayer);
sublayer.on('error', function(err) {
cartodb.log.log('error: ' + err);
});
})
.on('error', function() {
cartodb.log.log("some error occurred");
});
map = new google.maps.Map(document.getElementById('map'), mapOptions);
// Define the LatLng coordinates for the polygon's path.
var triangleCoords = [ new google.maps.LatLng(26.1750729378,50.5527011926),new google.maps.LatLng(26.1750278514,50.5528370586),new google.maps.LatLng(26.1749037197,50.5527864969),new google.maps.LatLng(26.1749497896,50.5526475251),new google.maps.LatLng(26.1750711189,50.5526969966),new google.maps.LatLng(26.1750729378,50.5527011926), ];
// Construct the polygon.
var bermudaTriangle = new google.maps.Polygon({
paths: triangleCoords,
strokeColor: '#FFF',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#EA4A38',
fillOpacity: 0.75
});
bermudaTriangle.setMap(map);
map.setMap(map);
}
window.onload = main;
My mistake.
map = new google.maps.Map(document.getElementById('map'), mapOptions);
Was there twice.
Related
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();
I make polygon drawing on my map.
Here is function for drawingManager
drawingManager = new google.maps.drawing.DrawingManager({
drawingMode: google.maps.drawing.OverlayType.RECTANGLE,
drawingControlOptions: {
drawingModes: [
google.maps.drawing.OverlayType.RECTANGLE,
google.maps.drawing.OverlayType.POLYGON
]
},
polygonOptions: {
fillColor: 'green',
fillOpacity: 0.4,
strokeWeight: 1,
clickable: true,
zIndex: 1,
editable: false
}
});
I need to calculate bounds for polygon. I read, that I cannot do it via .getBounds like with square.
So I found here answer
I tried one of answers.
So now my code looks like this.
drawingManager.addListener('polygoncomplete', function (polygon) {
var bounds = new google.maps.LatLngBounds();
polygon.forEach(function (feature) {
if (feature.getGeometry().getType() === 'Polygon') {
feature.getGeometry().forEachLatLng(function (latlng) {
bounds.extend(latlng);
});
}
});
console.dir(bounds);
});
and in console I get this error.
Index.js:1673 Uncaught TypeError: polygon.forEach is not a function
at this row polygon.forEach(function (feature) {
Where is problem and how I can solve it?
See the documentation:
A polygon has a .getPaths() method, which returns a MVCArray of LatLng objects.
drawingManager.addListener('polygoncomplete', function(polygon) {
var bounds = new google.maps.LatLngBounds();
polygon.getPaths().forEach(function(path) {
path.forEach(function(latlng) {
bounds.extend(latlng);
map.fitBounds(bounds);
});
});
});
proof of concept fiddle
code snippet:
function initialize() {
var map = new google.maps.Map(
document.getElementById("map_canvas"), {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var drawingManager = new google.maps.drawing.DrawingManager({
map: map,
drawingMode: google.maps.drawing.OverlayType.RECTANGLE,
drawingControlOptions: {
drawingModes: [
google.maps.drawing.OverlayType.RECTANGLE,
google.maps.drawing.OverlayType.POLYGON
]
},
polygonOptions: {
fillColor: 'green',
fillOpacity: 0.4,
strokeWeight: 1,
clickable: true,
zIndex: 1,
editable: false
}
});
drawingManager.addListener('polygoncomplete', function(polygon) {
var bounds = new google.maps.LatLngBounds();
polygon.getPaths().forEach(function(path) {
path.forEach(function(latlng) {
bounds.extend(latlng);
map.fitBounds(bounds);
});
});
});
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry,drawing&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="map_canvas"></div>
While it's not documented here:
https://developers.google.com/maps/documentation/javascript/reference/polygon
The Google Maps API for Polygons does have a getBounds() method.
The API documentation should be updated to include:
getBounds()
Parameters: None
Return Value: LatLngBounds
Returns the bounds of the Polygon.
\\ define map up here, draw polygons
let bounds = polygon.getBounds();
let rect = new google.maps.Rectangle({
bounds: bounds,
map: thisMap
});
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);
}
}
I want to define the longitude latitude once. Right now it only works if it's defined twice.
I've moved things around but all I've managed is a broken map. The font icon only shows when long and lat are in there twice.
Here's my code:
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(27.86336,-101.130738),
zoom: 16,
disableDefaultUI: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("google-map"), mapOptions);
new google.maps.Marker({
map: map,
icon: {
path: fontawesome.markers.EXCLAMATION,
scale: 0.5,
strokeWeight: 0,
strokeColor: 'transparent',
strokeOpacity: 0,
fillColor: 'red',
fillOpacity: 1,
},
clickable: false,
position: new google.maps.LatLng(27.86336,-101.130738)
});
}
google.maps.event.addDomListener(window, "load", initialize);
I've used the font marker solution from here: Using Icon Fonts as Markers in Google Maps V3 if that helps
You can merely do:
function initialize() {
var myLatLng = new google.maps.LatLng(27.86336. -101.130738);
var mapOptions = {
center: myLatLng,
zoom: 16,
disableDefaultUI: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("google-map"), mapOptions);
new google.maps.Marker({
map: map,
icon: {
path: fontawesome.markers.EXCLAMATION,
scale: 0.5,
strokeWeight: 0,
strokeColor: 'transparent',
strokeOpacity: 0,
fillColor: 'red',
fillOpacity: 1,
},
clickable: false,
position: myLatLng
});
}
google.maps.event.addDomListener(window, "load", initialize);
As long as you declare the variable within scope you shouldn't have any issues?
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(...)