Javascript Timeout function with Google Maps API Polygons - javascript

I am currently trying to create a program that increases the opacity of a polygon every 2 seconds until its non-transparent. I eventually want to do this with multiple polygons to relay data to the user over time, but I am simply trying to get one polygon to work. The code is written in Javascript and uses the timeout function to do so.
The code is supposed to draw a red square one the map with opacity 0.1, then 2 seconds later draw a similar square with opacity at 0.2. This process goes on until the opacity is equal to 1. The problem is that the program skips the first 9 squares (where opacity < 1) and draws the final square (opacity = 1). I believe that there may be a problem with how I am doing my delay.
Below is my sample code:
<!DOCTYPE HTML>
<html>
<head>
<style>
#map {
height: 100%;
}
#tabs{
width: 100%;
}
html, body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<script>
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 11,
center: {lat: 33.678, lng: -116.243},
mapTypeId: 'terrain'
});
for(i = 0.1; i < 1; i+=0.1){
setTimeout(function(){
var rectangle = new google.maps.Rectangle({
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: i,
map: map,
bounds: {
north: 33.685,
south: 33.671,
east: -116.234,
west: -116.251
}
});
}, 1000+i*20000)
}
}
</script>
<div id="map"></div>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
</script>
</body>
</html>

I slightly modified your code and implemented it with setInterval() function. Also please note that there is no need to create new instance of polygon inside a loop, you can just change polygon options.
code snippet:
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 11,
center: {lat: 33.678, lng: -116.243},
mapTypeId: 'terrain'
});
var m_opacity = 0.1;
var rectangle = new google.maps.Rectangle({
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: m_opacity,
map: map,
bounds: {
north: 33.685,
south: 33.671,
east: -116.234,
west: -116.251
}
});
var m_timer = window.setInterval(function(){
m_opacity += 0.1;
if (m_opacity <= 1.0) {
rectangle.setOptions({
fillOpacity: m_opacity
});
}
if (m_opacity === 1.0) {
window.clearInterval(m_timer);
}
}, 2000);
}
#map {
height: 100%;
}
#tabs{
width: 100%;
}
html, body {
height: 100%;
margin: 0;
padding: 0;
}
<div id="map"></div>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDztlrk_3CnzGHo7CFvLFqE_2bUKEq1JEU&v=3&libraries=places&callback=initMap"></script>
You can see this sample on jsbin as well: http://jsbin.com/yepagec/edit?html,output

Related

I want google map like this Multiple Polyline, can Multiple select

I want google map like this Multiple Polyline, can Multiple select.
Multiple Polyline
var geocoder;
var map;
var polyline;
positions = [new google.maps.LatLng(37.441883,-122.143019),
new google.maps.LatLng(37.45296,-122.181725)];
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
});
$("#chkRouteLines").click(function () {
if (!polyline || !polyline.setMap) {
polyline = new google.maps.Polyline({
path: positions,
strokeColor: "#FF0000",
strokeOpacity: 1.0,
strokeWeight: 2,
visible: true
});
}
if ($(this).is(':checked')) {
polyline.setMap(map);
} else {
polyline.setMap(null);
}
})
}
google.maps.event.addDomListener(window, "load", initialize);
html, body, #map_canvas {
height: 90%;
width: 100%;
margin: 0px;
padding: 0px
<div id="map_canvas" style="border: 2px solid #3872ac;"></div>
<input id="chkRouteLines" value="click" type="checkbox" />
you can google developers documents.For example this link:
https://developers.google.com/maps/documentation/javascript/examples/polyline-complex
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Complex Polylines</title>
<style>
/* 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;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
// This example creates an interactive map which constructs a polyline based on
// user clicks. Note that the polyline only appears once its path property
// contains two LatLng coordinates.
var poly;
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 7,
center: {lat: 41.879, lng: -87.624} // Center the map on Chicago, USA.
});
poly = new google.maps.Polyline({
strokeColor: '#000000',
strokeOpacity: 1.0,
strokeWeight: 3
});
poly.setMap(map);
// Add a listener for the click event
map.addListener('click', addLatLng);
}
// Handles click events on a map, and adds a new point to the Polyline.
function addLatLng(event) {
var path = poly.getPath();
// Because path is an MVCArray, we can simply append a new coordinate
// and it will automatically appear.
path.push(event.latLng);
// Add a new marker at the new plotted point on the polyline.
var marker = new google.maps.Marker({
position: event.latLng,
title: '#' + path.getLength(),
map: map
});
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
</script>
</body>
</html>

Opening an InfoWindow from a clickable Polygon Googlemaps

In researching the answer I've consulted the API documentation and example, many similar queries on stackflow and some Youtube examples but none are exactly what I'm looking to create and I can't fathom where I'm going wrong.
In this instance we wish the infowindow to appear by clicking within the defined border of the polygon, not by selecting a marker. I understand Googlemaps lets you do this as long as you give your infowindow a LatLng position.
What I can't understand is why the infowindow is not opening...
Please could you review code and let me know if you can spot anything obvious I'm missing. (Hope it's clear in the code notes but I'm looking to create many different are polygons across the same map)
<!DOCTYPE html>
<html>
<head>
<title>TBC</title>
<meta name="viewport" content="initial-scale=1.0">
<meta charset="utf-8">
<style>
/* 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;
}
#myDIV {
width: 100%;
padding: 50px 0;
text-align: center;
background-color: lightblue;
margin-top:20px;
}
</style>
</head>
<body>
<div id="map"style="width:800px;height:1200px;"></div>
<script>
var map;
function initMap() {{
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 17.247253, lng: 79.1},
zoom: 6,
mapTypeId: 'satellite'
});
//BEGINNING AREA CODE 1
// Define the LatLng coordinates for the polygon.
var hyderabadCoords = [
{lat:17.3876090549752,lng:78.5106470783611},
{lat:17.4637690550461,lng:78.5161870783663},
{lat:17.4391290550232,lng:78.4386270782939},
{lat:17.3876090549752,lng:78.5106470783611},
];
// Construct the polygon.
var hyderabadBorder = new google.maps.Polygon({
paths: hyderabadCoords,
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 3,
fillColor: '#FF0000',
fillOpacity: 0.0
});
hyderabadBorder.setMap(map);
//Content of infobox
var hyderLatLng = {lat: 17.39, lng: 78.50};
var contentString = "TBC"
var hyderinfowindow = new google.maps.InfoWindow({
content: contentString,
position:hyderLatLng
});
// Add a listener for the click event.
hyderabadBorder.addListener('click', showArrays);
hyderinfowindow = new google.maps.InfoWindow;
}
//END AREA CODE 1
//BEGINNING AREA CODE 2...(Repeat 1 with new area details)
//END ALL AREA CODES
/** #this {google.maps.Polygon} */
function showArrays(event) {
var vertices = this.getPath();
}
}
</script>
<script src="https://maps.googleapis.com/maps/api/js? key=YOUR_API_KEY&callback=initMap"
async defer></script>
</body>
</html>
You have 2 issues:
you are overwriting the InfoBox that has the content in it with one that is empty:
hyderinfowindow = new google.maps.InfoWindow;
You are never calling hyderinfowindow.open(map);
function showArrays(event) {
hyderinfowindow.open(map);
}
proof of concept fiddle
code snippet:
var map;
function initMap() {
{
map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: 17.247253,
lng: 79.1
},
zoom: 9,
mapTypeId: 'satellite'
});
// Construct the polygon.
var hyderabadBorder = new google.maps.Polygon({
paths: hyderabadCoords,
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 3,
fillColor: '#FF0000',
fillOpacity: 0.0
});
hyderabadBorder.setMap(map);
//Content of infobox
var hyderLatLng = {
lat: 17.39,
lng: 78.50
};
var contentString = "TBC"
var hyderinfowindow = new google.maps.InfoWindow({
content: contentString,
position: hyderLatLng
});
// Add a listener for the click event.
hyderabadBorder.addListener('click', showArrays);
}
//END AREA CODE 1
//BEGINNING AREA CODE 2...(Repeat 1 with new area details)
//END ALL AREA CODES
/** #this {google.maps.Polygon} */
function showArrays(event) {
hyderinfowindow.open(map);
}
}
google.maps.event.addDomListener(window, "load", initMap);
//BEGINNING AREA CODE 1
// Define the LatLng coordinates for the polygon.
var hyderabadCoords = [
{
lat: 17.3876090549752,
lng: 78.5106470783611
}, {
lat: 17.4637690550461,
lng: 78.5161870783663
}, {
lat: 17.4391290550232,
lng: 78.4386270782939
}, {
lat: 17.3876090549752,
lng: 78.5106470783611
},
];
/* 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,
#map {
height: 100%;
margin: 0;
padding: 0;
}
#myDIV {
width: 100%;
padding: 50px 0;
text-align: center;
background-color: lightblue;
margin-top: 20px;
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map"></div>

google maps infinite line / increase length or lat lng calculation

Hey there i´m trying to find a way to just increase the length of a line without changing the orientation
i tried this with Polyline
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 37.4419, lng: -122.1419},
zoom: 8
});
var line = new google.maps.Polyline({
path: [new google.maps.LatLng(37.4419, -122.1419), new google.maps.LatLng(37.4519, -122.1519)],
strokeColor: "#FF0000",
strokeOpacity: 1.0,
strokeWeight: 10,
geodesic: true,
map: map
});
}
and it works as expected
but i rather want it like
or
i only have the two coordinates from first example
it should be geodesic and theoreticaly idealy arround the globe back at same start so it will be like endless
i also tried to find out a way to calculate the some more far coordinates but searching is a mess because everboidy want to be found for caluclating distances.
so having two coordinates following the "line-through orientation" of but have high distance like some thousand kilometers pls let me know
You can use the Google Maps Javascript API Geometry library to compute the heading of the line and extend it an arbitrarily long distance along that heading.
code snippet::
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: 37.4419,
lng: -122.1419
},
zoom: 8
});
var line = new google.maps.Polyline({
path: [new google.maps.LatLng(37.4419, -122.1419), new google.maps.LatLng(37.4519, -122.1519)],
strokeColor: "#FF0000",
strokeOpacity: 1.0,
strokeWeight: 10,
geodesic: true,
map: map
});
// extend line from each end along its existing heading
// pick 20e6 meters as an arbitrary length
var lineHeading = google.maps.geometry.spherical.computeHeading(line.getPath().getAt(0), line.getPath().getAt(1));
var newPt0 = google.maps.geometry.spherical.computeOffset(line.getPath().getAt(0), 20000000, lineHeading);
line.getPath().insertAt(0, newPt0);
var newPt1 = google.maps.geometry.spherical.computeOffset(line.getPath().getAt(1), 20000000, lineHeading + 180);
line.getPath().push(newPt1);
}
google.maps.event.addDomListener(window, "load", initMap);
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry"></script>
<div id="map"></div>

How to create a highlight an image when double clicked?

I am trying to display a highlighted circle when the user double clicks on a certain part of an image. For example, if the image is a map of a city, and they double click on coord: (X, Y), I want the highlighted circle's center to be at (X, Y) and the radius would vary on the item that they clicked on.
Here is what I have so far:
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?sensor=false">
</script>
<script type="text/javascript">
function showMap(){
var mapOptions = {
zoom: 19,
center: new google.maps.LatLng(x, y),//let z, y be some coord
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDoubleClickZoom: true,
disableDefaultUI: true,
zoomControl: false,
draggable: false,
scrollwheel: false
}
map = new google.maps.Map(document.getElementById("myMap"),
mapOptions);
google.maps.event.addListener(map, 'dblclick', doubleClicked);
}
function doubleClicked(e){//highlight the area with a circle
//alert("lat: " + e.latLng.lat() + "\nlong: " + e.latLng.lng());
}
</script>
HTML
<div id="myMap" ></div>
CSS
#myMap {
margin-left: auto;
margin-right: auto;
width: 1200px;
height: 800px
}
Solution with help from #Aamir Sarwar:
var circle = new google.maps.Circle({
strokeColor: '#FFFFFF',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35,
map: map,
center: {lat: X, lng: Y}
radius: 10
});
check below example copy from this link...hope it may help you https://developers.google.com/maps/documentation/javascript/examples/rectangle-simple?hl=en
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Rectangles</title>
<style>
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
}
</style>
<script>
// This example adds a red rectangle to a map.
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 11,
center: {lat: 33.678, lng: -116.243},
mapTypeId: google.maps.MapTypeId.TERRAIN
});
var rectangle = new google.maps.Rectangle({
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35,
map: map,
bounds: {
north: 33.685,
south: 33.671,
east: -116.234,
west: -116.251
}
});
}
</script>
</head>
<body>
<div id="map"></div>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&signed_in=true&callback=initMap"></script>
</body>
</html>
Here's the general outline:
myMap should be position:relative
Add mouse events on myMap to track X,Y of the mouse position
in doubleClicked method, create div that would be displayed as circle. Also it should be position:absolute
add that element to the myMap and change its CSS: left to mouse X position and top to mouse Y position

Google Maps API Circle Intersect Detection

I'm trying to figure out of it's possible to detect when two Google Maps circles (around markers) intersect or bump into each other.
What I want to accomplish is, if two circles intersect, I want to raise an event. I'm not sure if this is possible though.
Calculate the distance between the centers of the circles, if it is less than the sum of the radius of the two circles, they intersect.
proof of concept fiddle
(based off of the code in Larry Dukek's answer, but using native Google Maps Javascript API v3 functions from the geometry library)
code snippet:
let map;
function initMap() {
// Create the map.
map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: 41.081301,
lng: -98.214219
},
zoom: 25
});
var c0 = new google.maps.Circle({
strokeColor: '#0000FF',
strokeOpacity: 1,
strokeWeight: 1,
fillColor: '#0000FF',
fillOpacity: 0.2,
map: map,
center: {
lat: 41.082953,
lng: -98.215285
},
radius: 200
});
var c1 = new google.maps.Circle({
strokeColor: '#FF0000',
strokeOpacity: 1,
strokeWeight: 1,
fillColor: '#FF0000',
fillOpacity: 0.2,
map: map,
center: {
lat: 41.081070,
lng: -98.214027
},
radius: 34.692866520
});
console.log("c1 & c0 hasIntersections returns:" + hasIntersections(c1, c0));
var c2 = new google.maps.Circle({
strokeColor: '#00FF00',
strokeOpacity: 1,
strokeWeight: 1,
fillColor: '#00FF00',
fillOpacity: 0.2,
map: map,
center: {
lat: 41.083313,
lng: -98.211635
},
radius: 34.692866520
});
console.log("c2 & c0 hasIntersections returns:" + hasIntersections(c2, c0));
}
function hasIntersections(circle0, circle1) {
var center0 = circle0.getCenter();
var center1 = circle1.getCenter();
var maxDist = circle0.getRadius() + circle1.getRadius();
var actualDist = google.maps.geometry.spherical.computeDistanceBetween(center0, center1);
return maxDist >= actualDist;
}
/* 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>Circles</title>
<script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
<!-- jsFiddle will insert css and js -->
</head>
<body>
<div id="map"></div>
<!-- Async script executes immediately and must be after any DOM elements used in callback. -->
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap&libraries=geometry&v=weekly&channel=2" async></script>
</body>
</html>
Here is some JavaScript that will detect if two circles intersect
var e = Math; // shortcut for the mathematical function
var D2R = e.PI/180.0; // value used for converting degrees to radians
Number.prototype.toRadians = function() {
return this * D2R;
};
function distance(lat0,lng0,lat1,lng1){
// convert degrees to radians
var rlat0 = lat0.toRadians();
var rlng0 = lng0.toRadians();
var rlat1 = lat1.toRadians();
var rlng1 = lng1.toRadians();
// calculate the differences for both latitude and longitude (the deltas)
var Δlat=(rlat1-rlat0);
var Δlng=(rlng1-rlng0);
// calculate the great use haversine formula to calculate great-circle distance between two points
var a = e.pow(e.sin(Δlat/2),2) + e.pow(e.sin(Δlng/2),2)*e.cos(rlat0)*e.cos(rlat1);
var c = 2*e.asin(e.sqrt(a));
var d = c * 6378137; // multiply by the radius of the great-circle (average radius of the earth in meters)
return d;
}
function hasIntersections(circle0,circle1){
var center0 = circle0.getCenter();
var center1 = circle1.getCenter();
var maxDist = circle0.getRadius()+circle1.getRadius();
var actualDist = distance(center0.lat(),center0.lng(),center1.lat(),center1.lng());
return maxDist>=actualDist;
}
Just call hasIntersections with the references to your circles. Here is an example that showing two circles almost touching (returning false) and if you change the zero to a one in c1 they will touch (returning true).
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 41.081301, lng: -98.214219},
zoom: 25
});
var c0 = new google.maps.Circle({
strokeOpacity: .1,
strokeWeight: 1,
fillColor: '#0000FF',
fillOpacity: .2,
map: map,
center: {lat:41.082953, lng: -98.215285},
radius: 200
});
var c1 =new google.maps.Circle({
strokeOpacity: .1,
strokeWeight: 1,
fillColor: '#FF0000',
fillOpacity: .2,
map: map,
center: {lat:41.081070, lng: -98.214027},
radius: 34.692866520
});
console.log(hasIntersections(c1,c0));

Categories

Resources