The correct way to hide a polyline? - google-maps-api-3

I´ve a function that show a polyline on a map, this part is working, now I want to implement a function that hides the polyline, but I can´t find my mistake, thanks in advance.
function cargaMapaCYL(mapa, varControl){
var limite = null;
limite = [
new google.maps.LatLng(42.49956716,-7.019005501),
new google.maps.LatLng(42.49947126,-7.029286373),
new google.maps.LatLng(42.50904062,-7.049299123),
new google.maps.LatLng(42.50722622,-7.069103626),
new google.maps.LatLng(42.50452387,-7.000150672),
new google.maps.LatLng(42.49348015,-6.983058917),
new google.maps.LatLng(42.49843269,-6.971666546),
new google.maps.LatLng(42.51765791,-6.956909023),
new google.maps.LatLng(42.52010069,-6.927429186),
new google.maps.LatLng(42.50992238,-6.914231493),
new google.maps.LatLng(42.50096695,-6.879679821),
new google.maps.LatLng(42.48775868,-6.857775832),
new google.maps.LatLng(43.23907504,-3.293216584)], "#000000", 5);
var contorno= new google.maps.Polyline({
path: limite,
strokeColor: "#000000",
strokeOpacity: 1.0,
strokeWeight: 2
});
if(varControl==true){
contorno.setMap(mapa);
}
if(varControl==false){
contorno.setMap(null);
}
}

You only need to create the Polyline once. Put it into a global var contorno = ... Then you can create a toggle function using the setVisible(boolean) method.
if(contorno.getVisible()){
contorno.setVisible(false);
else{
contorno.setVisible(true);
}
// or
contorno.getVisible() ? contorno.setVisible(false) : contorno.setVisible(true);
Blow is an example which hides the path after 3 seconds.
/* 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;
}
<div id="map"></div>
<script>
// This example creates a 2-pixel-wide red polyline showing the path of William
// Kingsford Smith's first trans-Pacific flight between Oakland, CA, and
// Brisbane, Australia.
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 3,
center: {lat: 0, lng: -180},
mapTypeId: 'terrain'
});
var flightPlanCoordinates = [
{lat: 37.772, lng: -122.214},
{lat: 21.291, lng: -157.821},
{lat: -18.142, lng: 178.431},
{lat: -27.467, lng: 153.027}
];
var flightPath = new google.maps.Polyline({
path: flightPlanCoordinates,
geodesic: true,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 2
});
flightPath.setMap(map);
setTimeout(function() {
alert('hide path');
flightPath.setVisible(false);
}, 3000);
}
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?callback=initMap"></script>

Everytime your function is called, it creates a new polyline. Which is either added to the map or not.
Persumably you want be able to call the function once with true to add the line, then again with false to remove it. At the moment, when you call it a second time, its creates a new line and doesn't add it to the map. It does not touch the original line, already added to the map.
One way is too keep the line in a global variable. Then you can refer to the exact same object between calls.
var contorno = null;
function cargaMapaCYL(mapa, varControl){
if (!contorno) {
var limite = [...], "#000000", 5);
contorno= new google.maps.Polyline({...});
}
if(varControl){
contorno.setMap(mapa);
} else {
contorno.setMap(null);
}
}

Related

center and fit boundaries of geojson multiple polygon data

I am trying to center and fit the boundaries of multiple geojson polygon features on my google.maps.Map.
See this non geojson fiddle recreating the effect i'm after.
Is there an easy Google Map API 3 function to do this for geojson data?
See my code below and fiddle here
var map;
window.initMap = function() {
var mapProp = {
center: new google.maps.LatLng(51.8948201,-0.7333298),
zoom: 17,
mapTypeId: 'satellite'
};
map = new google.maps.Map(document.getElementById("map"), mapProp);
map.data.loadGeoJson('https://api.myjson.com/bins/g0tzw');
map.data.setStyle({
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35
});
var bounds = new google.maps.LatLngBounds();
map.fitBounds(bounds);
map.setCenter(bounds.getCenter());
}
I need expert pointers on cleanest and best way approach this.
See working demo of my code above in fiddle.
http://jsfiddle.net/joshmoto/fe2vworc/
I've included my geojson inline so you can see the polygons on the map.
Here is a quick example of how you can get your features bounds. This will just get each feature bounds, extend a LatLngBounds object and then fit the map with these bounds.
var map;
function initialize() {
map = new google.maps.Map(document.getElementById('map-canvas'), {
zoom: 10,
center: {
lat: 0,
lng: 0
}
});
var permits = {
type: "FeatureCollection",
id: "permits",
features: [{
type: "Feature",
properties: {
name: "Alpha Field"
},
geometry: {
type: "Polygon",
coordinates: [
[
[-0.72863, 51.895995],
[-0.730022, 51.896766],
[-0.730754, 51.896524],
[-0.731234, 51.896401],
[-0.731832, 51.896294],
[-0.732345, 51.896219],
[-0.732945, 51.896102],
[-0.732691, 51.895774],
[-0.732618, 51.895531],
[-0.732543, 51.895359],
[-0.73152, 51.894751],
[-0.731037, 51.894488],
[-0.730708, 51.894324],
[-0.72863, 51.895995]
]
]
}
},
{
type: "Feature",
properties: {
name: "Beta Field"
},
geometry: {
type: "Polygon",
coordinates: [
[
[-0.728004, 51.895658],
[-0.72863, 51.895995],
[-0.730708, 51.894324],
[-0.731217, 51.893784],
[-0.730992, 51.893709],
[-0.730793, 51.893567],
[-0.730734, 51.893435],
[-0.730761, 51.89333],
[-0.729696, 51.893244],
[-0.729391, 51.89314],
[-0.729249, 51.893586],
[-0.728991, 51.894152],
[-0.728525, 51.894983],
[-0.728004, 51.895658]
]
]
}
}
]
};
google.maps.event.addListenerOnce(map, 'idle', function() {
// Load GeoJSON.
map.data.addGeoJson(permits);
// Create empty bounds object
var bounds = new google.maps.LatLngBounds();
// Loop through features
map.data.forEach(function(feature) {
var geo = feature.getGeometry();
geo.forEachLatLng(function(LatLng) {
bounds.extend(LatLng);
});
});
map.fitBounds(bounds);
});
}
initialize();
#map-canvas {
height: 150px;
}
<div id="map-canvas"></div>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
Props to #MrUpsidown for providing the working method to fitBounds.
I'm posting this answer to show my final solution based on #MrUpsidown answer using GeoJson data via loadGeoJson()
Here is my readable GeoJson here http://myjson.com/g0tzw
// initiate map
window.initMap = function() {
// permits json
var permits = 'https://api.myjson.com/bins/g0tzw';
// map properties
var mapProp = {
zoom: 17,
mapTypeId: 'satellite'
};
// google map object
var map = new google.maps.Map(document.getElementById("map"), mapProp);
// load GeoJSON.
map.data.loadGeoJson(permits, null, function () {
// create empty bounds object
var bounds = new google.maps.LatLngBounds();
// loop through features
map.data.forEach(function(feature) {
var geo = feature.getGeometry();
geo.forEachLatLng(function(LatLng) {
bounds.extend(LatLng);
});
});
// fit data to bounds
map.fitBounds(bounds);
});
// map data styles
map.data.setStyle({
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35
});
}
I'm calling initMap via...
<script async defer src="https://maps.googleapis.com/maps/api/js?key=<?=$gmap_api?>&callback=initMap"></script>
See working demo here.
http://jsfiddle.net/joshmoto/eg3vj17m/

How do I redraw a google maps marker on click?

I have a google map with a set of map markers. I chose to draw the map markers with a function called pinSymbol() - instead of using the default image.
I want to change the color of the pin when it is clicked, but I can't get it to update. With the current code I can change the property of the icon, I can see this with console.log(marker), however it won't update the color on the map.
Question: How do I redraw the icon on click?
This is my code.
// Go through all restaurants and get facebook info,
// then create a marker for each one.
restaurants.forEach(function(restaurant){
getFacebookInfo(restaurant);
}); // end forEach loop
// Get data from Facebook Graph API and create a marker
function getFacebookInfo(restaurant){
$.ajax({
url : '/restaurants/' + restaurant.id,
type : 'GET',
dataType:'json',
success : function(data) {
restaurant.about = data.about;
createMarker(restaurant);
},
error : function(request, error) {
console.log(error);
alert("We're having some trouble getting a restaurant's info from Facebook. " +
"Please check your internet connection and try refreshing the page.")
}
});
}
// Create a marker on the map for a location
function createMarker(restaurant){
var position = restaurant.location;
var infowindow = new google.maps.InfoWindow({
maxWidth: 200
});
restaurant.marker = new google.maps.Marker({
position: position,
map: map,
icon: pinSymbol('#CD212A', '#CD212A'),
name: restaurant.name,
id: restaurant.id,
about: restaurant.about,
animation: google.maps.Animation.DROP
});
// Push the marker to array of markers
markers.push(restaurant.marker);
// Call populateInfoWindow function
populateInfoWindow(restaurant.marker, infowindow);
// Add infowindow as a property to restaurant
// this makes it available for use outside this function.
restaurant.infowindow = infowindow;
This is where I'm stuck:
// Open infowindow when marker is clicked and change color
restaurant.marker.addListener('click', function(){
this.icon = pinSymbol('#EED4D9', '#EED4D9');
console.log(restaurant.marker);
infowindow.open(map, this);
});
}
pinSymbol Function
// Create pin for google map marker
function pinSymbol(color, strokeColor) {
return {
path: 'M 0,0 C -2,-20 -10,-22 -10,-30 A 10,10 0 1,1 10,-30 C 10,-22 2,-20 0,0 z',
fillColor: color,
fillOpacity: 1,
strokeColor: strokeColor,
strokeWeight: 1,
scale: 1,
labelOrigin: new google.maps.Point(0,-29)
};
}
There is no (documented) .icon property of a marker. Don't use it. Use the documented .setIcon method:
// Open infowindow when marker is clicked and change color
restaurant.marker.addListener('click', function() {
this.setIcon(pinSymbol('#EED4D9', '#EED4D9'));
console.log(restaurant.marker);
infowindow.open(map, this);
});
proof of concept fiddle
code snippet:
var geocoder;
var map;
var markers = [];
function initialize() {
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
});
createMarker({
name: "center",
id: 2,
about: "",
location: {
lat: 37.4419,
lng: -122.1419
}
});
}
google.maps.event.addDomListener(window, "load", initialize);
// Create a marker on the map for a location
function createMarker(restaurant) {
var position = restaurant.location;
var infowindow = new google.maps.InfoWindow({
maxWidth: 200
});
restaurant.marker = new google.maps.Marker({
position: position,
map: map,
icon: pinSymbol('#CD212A', '#CD212A'),
name: restaurant.name,
id: restaurant.id,
about: restaurant.about,
animation: google.maps.Animation.DROP
});
// Push the marker to array of markers
markers.push(restaurant.marker);
// Call populateInfoWindow function
populateInfoWindow(restaurant.marker, infowindow);
// Add infowindow as a property to restaurant
// this makes it available for use outside this function.
restaurant.infowindow = infowindow;
// Open infowindow when marker is clicked and change color
restaurant.marker.addListener('click', function() {
if (this.getIcon().fillColor != "#EED4D9") {
this.setIcon(pinSymbol('#EED4D9', '#EED4D9'));
} else {
this.setIcon(pinSymbol('#CD212A', '#CD212A'));
}
console.log(restaurant.marker);
infowindow.open(map, this);
});
}
// Create pin for google map marker
function pinSymbol(color, strokeColor) {
return {
path: 'M 0,0 C -2,-20 -10,-22 -10,-30 A 10,10 0 1,1 10,-30 C 10,-22 2,-20 0,0 z',
fillColor: color,
fillOpacity: 1,
strokeColor: strokeColor,
strokeWeight: 1,
scale: 1,
labelOrigin: new google.maps.Point(0, -29)
};
}
function populateInfoWindow(marker, infowindow) {
infowindow.setContent("content");
};
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map_canvas"></div>

Google Maps Data Layer features not rendering after 1st feature deletion

I am trying to allow a user to draw a shape in Google Maps using the map.data features layer. As soon as the user finishes drawing, I want to process the coordinates of the shapes they just drew and then immediately remove it from the map. The first shape deletes fine, but after the first they still process and appear to empty out of the object (tested by using the map.data.toGeoJson to log it to the console where it shows the map.data object but with no features present) but they are still visible on the map.
To see what is happening, in the fiddle draw a polygon and on completion (double click) it disappears because it is deleted after processing (which is what should happen). However, when a second or more polygons are drawn they stay visible on the map.
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: -34.397,
lng: 150.644
},
zoom: 8
});
map.data.setControls(['Point', 'LineString', 'Polygon']);
map.data.addListener('addfeature', function(event) {
event.feature.getGeometry().forEachLatLng(function(latLng) {
//do stuff with the feature
});
map.data.remove(event.feature);
});
}
Fiddle: https://jsfiddle.net/km76tvhp/13/
This is strange behavior and it could possibly be a bug. As a workaround, you could use the Drawing Library. Here is an example below which uses the google.maps.drawing.DrawingManager. It's very similar to drawing using the google.maps.Data class.
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: -34.397,
lng: 150.644
},
zoom: 8
});
var drawingManager = new google.maps.drawing.DrawingManager({
drawingControlOptions: {
drawingModes: ['marker', 'polygon', 'polyline']
},
polygonOptions: {
editable: true,
draggable: true,
strokeColor: 'red'
}
});
drawingManager.setMap(map);
google.maps.event.addListener(drawingManager, 'polygoncomplete', function(polygon) {
polygon.getPath().getArray().forEach(function(latLng){
// do stuff with the feature
});
polygon.setMap(null);
});
}
#map {
height: 100%;
}
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
<div id="map"></div>
<script src="https://maps.googleapis.com/maps/api/js?callback=initMap&libraries=drawing" async defer></script>

svg static image within the area of a polygon

How do I get the svg image is static when I zoom in on the map, which always remains in the same place.
This is my fiddle
If I use png images works , but it is not visually well for me and is not what i'm looking for.
Help is appreciated
Sorry for my english.
new Fiddle
The anchor is expected to be a Point, not a LatLng.
The default-acnchor is the bottom-middle of the icon, as it seems you need to set it to the top-left, so it has to be:
new google.maps.Point(0,0)
When you want to have a scaled icon based on the zoom you must calculate the scale-property and re-assign the icon to the marker.
The formula would be(assuming the scale-factor at zoom 12 is 1):
Math.pow(2,map.getZoom()-12)
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(-32.95041520, -60.66641804),
zoom: 12,
mapTypeId: google.maps.MapTypeId.TERRAIN
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
triangleCoords = [
new google.maps.LatLng(-32.93831432, -60.69379806),
new google.maps.LatLng(-32.96337859, -60.67860603),
new google.maps.LatLng(-32.96352262, -60.66633224),
new google.maps.LatLng(-32.95041520, -60.66641807)
];
var bermudaTriangle = new google.maps.Polygon({
paths: triangleCoords,
IsInactivo: true
});
bermudaTriangle.setMap(map);
var bounds = new google.maps.LatLngBounds();
var i;
for (i = 0; i < triangleCoords.length; i++) {
bounds.extend(triangleCoords[i]);
}
console.log(bounds.getCenter());
centroPolygon = bounds.getCenter();
var inactive = new google.maps.MVCObject();
inactive.set('icon', {
path: 'M27.314 4.686c-3.022-3.022-7.040-4.686-11.314-4.686s-8.292 1.664-11.314 4.686c-3.022 3.022-4.686 7.040-4.686 11.314s1.664 8.292 4.686 11.314c3.022 3.022 7.040 4.686 11.314 4.686s8.292-1.664 11.314-4.686c3.022-3.022 4.686-7.040 4.686-11.314s-1.664-8.292-4.686-11.314zM28 16c0 2.588-0.824 4.987-2.222 6.949l-16.727-16.727c1.962-1.399 4.361-2.222 6.949-2.222 6.617 0 12 5.383 12 12zM4 16c0-2.588 0.824-4.987 2.222-6.949l16.727 16.727c-1.962 1.399-4.361 2.222-6.949 2.222-6.617 0-12-5.383-12-12z',
fillColor: '#FF5858',
fillOpacity: 0.4,
scale: 1,
strokeColor: '#FF5858',
strokeWeight: 1,
//set the anchor to the top left corner of the svg
anchor: new google.maps.Point(0, 0)
});
google.maps.event.addListener(map, 'zoom_changed', function() {
inactive.get('icon').scale = Math.pow(2, this.getZoom() - 12);
//tell the marker that the icon has changed
inactive.notify('icon');
});
google.maps.event.trigger(map, 'zoom_changed');
new google.maps.Marker({
map: map,
position: centroPolygon
}).bindTo('icon', inactive, 'icon');
}
google.maps.event.addDomListener(window, 'load', initialize)
html,
body,
#map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?v=3&.js"></script>
<div id="map-canvas"></div>

Problems in Creating InfoWindow on each individual circle with mouseover using Google Map API

I am having problems using Google Map API.
I want to plot circles on the map and create mouseover event on each circle to open an infowindow displaying the time value.
First problem is the infowindow content does not change for different circles.
Second problem is infowindow does not pop up for some reason.
Can someone help please?
Thanks
Codes are as followings:
function initialize() {
data={};
data[0]={
center: new google.maps.LatLng(51.49799,-0.196145),
population: 1000,
time:"2013-03-01T03:31:18Z"
};
data[1]={
center: new google.maps.LatLng(51.496294,-0.188184),
population: 1000,
time:"2013-03-01T13:21:15Z"
};
data[2]={
center: new google.maps.LatLng(51.497817,-0.178313),
population: 1000,
time:"2013-03-04T04:03:50Z"
};
var mapOptions = {
zoom: 15,
center: new google.maps.LatLng(51.494438, -0.188907),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map_canvas'),
mapOptions);
var movingColour= '#FF0000';
var counter=0;
for (var city in data) {
// Construct the circle for each value in citymap. We scale population by 20.
//movingColour=ColorLuminance(movingColour, -0.005) ;
var populationOptions = {
strokeOpacity: 0.35,
strokeWeight: 2,
strokeColor:movingColour,
fillColor:movingColour ,
fillOpacity: 0.35,
map: map,
clickable:true,
center: data[city].center,
radius: data[city].population / 20
};
var circle = new google.maps.Circle(populationOptions);
var infowindow =new google.maps.InfoWindow({
content: data[city].time
});
google.maps.event.addListener(circle, 'mouseover', function(ev) {
alert(infowindow.content);
infowindow.open(map,circle);
});
counter++;
}
google.maps.event.addDomListener(window, 'load', initialize);
}
This is a common problem usually seen with InfoWindows on markers and can be solved a number of ways. The InfoWindow isn't opening because the optional second parameter of .open can only be a marker, without that, you need to set the position at which the marker should open. I usually use function closure to solve the InfoWindow content problem (there are other ways):
function initialize() {
data={};
data[0]={
center: new google.maps.LatLng(51.49799,-0.196145),
population: 1000,
time:"2013-03-01T03:31:18Z"
};
data[1]={
center: new google.maps.LatLng(51.496294,-0.188184),
population: 1000,
time:"2013-03-01T13:21:15Z"
};
data[2]={
center: new google.maps.LatLng(51.497817,-0.178313),
population: 1000,
time:"2013-03-04T04:03:50Z"
};
var mapOptions = {
zoom: 15,
center: new google.maps.LatLng(51.494438, -0.188907),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map_canvas'),
mapOptions);
var movingColour= '#FF0000';
var counter=0;
for (var city in data) {
var populationOptions = {
strokeOpacity: 0.35,
strokeWeight: 2,
strokeColor:movingColour,
fillColor:movingColour ,
fillOpacity: 0.35,
map: map,
clickable:true,
center: data[city].center,
radius: data[city].population / 20
};
var circle = new google.maps.Circle(populationOptions);
createClickableCircle(map, circle, data[city].time);
counter++;
}
google.maps.event.addDomListener(window, 'load', initialize);
}
function createClickableCircle(map, circle, info){
var infowindow =new google.maps.InfoWindow({
content: info
});
google.maps.event.addListener(circle, 'mouseover', function(ev) {
// alert(infowindow.content);
infowindow.setPosition(circle.getCenter());
infowindow.open(map);
});
}
(you probably want to add a listener to close the InfoWindow.)
I rewrite a bit of your javascript to have better syntax and named variables which you had forgotten to define with var.
For example to define data={}; use var data=[]; since I can see below that you use it as an array containing objects. I also made a fix which stops flickering effect when you are moving your cursor over circles which has infowindow already opened:
// To stop flickering.. we wont reopen until necessary
// We open only if position has been changed or infowindow is not visible
if(infowindow.getPosition() !== this.getCenter() || infowindowClosed === true) {
// this can be used to access data values
infowindow.setContent(this.data.time);
infowindow.setPosition(this.getCenter());
infowindow.open(map);
infowindowClosed = false;
}
Other enhancements includes defining few of your variables as global above your initialize(); method, cheers.
Check out working fiddle with comments.

Resources