google maps v3 fill in circle completely - google-maps-api-3

I created a map which allows users to draw a circle around a point with a specified radius. For some reason the circle does not get completely filled in and this is especially noticeable when the map is more zoomed in. Perhaps someone has a solution to fill the circle completely even when viewed at at a higher zoom level
See code below
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0px; padding: 0px }
#map_canvas { height: 100% }
</style>
<script type="text/javascript"
src="http://maps.google.com/maps/api/js?sensor=false">
</script>
</script>
<script type= "text/javascript">
var geocoder;
var map;
var count=0;
//Store points in array
var points = [];
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions = {
zoom: 3,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"),myOptions);
}
function codeAddress() {
var address = document.getElementById("address").value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
}
else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
function plusCount(){
if (count==2){
count=0;
}
else{
count=count +1;
}
}
function drawCircle() {
var address=document.getElementById("address").value;
var radius=document.getElementById("radius").value;
var latitude=40;
var longitude=0;
geocoder.geocode( { 'address': address}, function(results, status){
if (status==google.maps.GeocoderStatus.OK){
latlng=(results[0].geometry.location);
latitude=latlng.lat();
longitude=latlng.lng();
alert(latitude);
alert(longitude);
alert (radius);
}
else{
alert("Geocode was not successful for the following reason: " + status);
}
});
//Degrees to radians
var d2r = Math.PI / 180;
alert("calc d2r " + d2r);
// Radians to degrees
var r2d = 180 / Math.PI;
alert("calc r2d " + r2d);
// Earth radius is 3,963 miles
var cLat = (radius / 3963) * r2d;
alert("calc cLat " + cLat);
var cLng = cLat / Math.cos(latitude * d2r);
alert("calc cLng " + cLng);
// Calculate the points
// Work around 360 points on circle
for (var i=0; i < 360; i++) {
var theta = Math.PI * (i/16);
// Calculate next X point
circleY = longitude + (cLng * Math.cos(theta));
// Calculate next Y point
circleX = latitude + (cLat * Math.sin(theta));
// Add point to array
points.push(new google.maps.LatLng(circleX, circleY));
};
alert("completed loop");
var colors=["#CD0000","#2E6444","#003F87" ];
var Polyline_Path = new google.maps.Polyline({
path: points,
strokeColor: colors[count],
// color of the outline of the polyline
strokeOpacity: 1,
// between 0.0 and 1.0
strokeWeight: 1,
// The stroke width in pixels
fillColor: colors[count],
fillOpacity: .5
});
Polyline_Path.setMap(map);
}
function clearMap(){
if(points){
for( i in points){
points[i].setMap(null);
}
points.length=0;
}}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="width:500px; height:460px;
-moz-outline-radius:20px; -moz-box-sizing:padding-box; -moz-outline- style:solid ;-moz-outline-color:#9FB6CD;
- moz-outline-width:10px;"></div>
<div>
Zip Code: <input id="address" type="textbox" value="">
Radius:<input id="radius" type="textbox" value="">
<input type="button" value="Find" onclick="codeAddress() ">
<input type="button" value="Draw Radius" onclick= "drawCircle() ; plusCount()">
<input type="button" value="Reset" onclick= "clearMap()">
</div>
</body>

It looks like you are drawing the circle manually, but you could use the
google.maps.Circle
which works for me and fills the circle entirely. Here is a snippet I use in my application, which works also in maximum zoom level:
var circ = new google.maps.Circle({
'center':lc,
'clickable':false,
'fillColor':"#00FFFF",
'fillOpacity':0.2,
'map':currentmap,
'radius':75,
'strokeColor':'#0000A0',
'strokeOpacity':'0.5'
});
lc is my center point, currentmap is the map div

This method works for me
var options = {
strokeColor: #CD0000,
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: #2E6444,
fillOpacity: 0.5,
map: map,
center: latlng,
radius: parseInt(radius)
};
var circle = new google.maps.Circle(options);

var drawInnerZone=
{
strokeColor: "#61A0A8",
strokeOpacity: 0.2,
strokeWeight: 1,
fillColor: "#61A0A8",
fillOpacity: 0.8,
map: map,
center: NearMatches['InnerZone'].center, //Latlng
radius: NearMatches['InnerZone'].Distance //radius
};
MatchZone1 = new google.maps.Circle(drawInnerZone);
it works for me..

the answer for richie work correctly on my project
function searchLocations() {
var image='image/male.png'
var a = document.getElementById("radiusSelect").value;
var address = document.getElementById("addressInput").value;
var geocoder = new google.maps.Geocoder();
geocoder.geocode({'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
icon: image
});
var circle = new google.maps.Circle({
map: map,
radius: parseInt(a), // 10 miles in metres
fillColor: '#AA0000'
});
circle.bindTo('center', marker, 'position');
searchLocationsNear(results[0].geometry.location);
}
else {
alert(address + ' not found');
}
});
}

Related

Add animated PNG. to polyline in google maps API

I'm trying to animate a icon over a polyline like in this example: https://developers-dot-devsite-v2-prod.appspot.com/maps/documentation/javascript/examples/overlay-symbol-animate.
It works but I want to add my own PNG as the icon that is being animated. This is what I tried:
var line = new google.maps.Polyline({
path: [{ lat: 25.774266, lng: -80.193659 }, { lat: 25.83333, lng: 25.83333 - 77.8999964 }],
icons: [{
icon: CruiseShip //This is my .PNG file
}],
strokeColor: '#ffffff',
strokeWeight: 1,
map: map
});
function animateCircle(line) {
var count = 0;
window.setInterval(function () {
count = (count + 1) % 200;
var icons = line.get('icons');
icons[0].offset = (count / 2) + '%';
line.set('icons', icons);
}, 20);
}
Using the lineSymbol object like in the example does work. How can I add a .PNG file to the polyline instead of the lineSymbol? Couldn't find any documentation on this.
The way you are trying to animate the icon only works for SVG Symbols.
Mike Williams wrote an extension to the Google Maps Javascript API v2 (now deprecated and turned off) called epoly which contains the method .GetPointAtDistance, which can be used to update the position of a "normal" icon along a polyline.
There is a interpolate method in the google.maps.geometry.spherical library which interpolates between two points, but isn't very accurate for large scale features.
proof of concept fiddle
code snippet:
// This example creates a 2-pixel-wide red polyline showing the path of
// the first trans-Pacific flight between Oakland, CA, and Brisbane,
// Australia which was made by Charles Kingsford Smith.
function initMap() {
updatePolylinePrototype();
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 3,
center: {
lat: 0,
lng: -180
},
mapTypeId: 'terrain'
});
var line = new google.maps.Polyline({
path: [{
lat: 25.774266,
lng: -80.193659
}, {
lat: 25.83333,
lng: 25.83333 - 77.8999964
}, {
lat: 28.411413,
lng: -16.5449611
}],
strokeColor: '#ffffff',
strokeWeight: 1,
map: map
});
var marker = new google.maps.Marker({
icon: {
url: "http://earth.google.com/images/kml-icons/track-directional/track-12.png",
anchor: new google.maps.Point(12, 12),
scaledSize: new google.maps.Size(24, 24),
},
position: line.getPath().getAt(0),
map: map
})
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < line.getPath().getLength(); i++) {
bounds.extend(line.getPath().getAt(i));
}
map.fitBounds(bounds);
animateShip(line, marker);
}
function animateShip(line, marker) {
var count = 0;
var lineDistance = 0;
for (var i = 1; i < line.getPath().getLength(); i++) {
lineDistance += google.maps.geometry.spherical.computeDistanceBetween(line.getPath().getAt(i - 1), line.getPath().getAt(i))
}
window.setInterval(function() {
count = (count + 1) % 200;
marker.setPosition(line.GetPointAtDistance(lineDistance - (lineDistance * count / 200)));
}, 20);
}
function updatePolylinePrototype() {
// === A method which returns a GLatLng of a point a given distance along the path ===
// === Returns null if the path is shorter than the specified distance ===
google.maps.Polyline.prototype.GetPointAtDistance = function(metres) {
// some awkward special cases
if (metres == 0) return this.getPath().getAt(0);
if (metres < 0) return null;
if (this.getPath().getLength() < 2) return null;
var dist = 0;
var olddist = 0;
for (var i = 1;
(i < this.getPath().getLength() && dist < metres); i++) {
olddist = dist;
dist += google.maps.geometry.spherical.computeDistanceBetween(this.getPath().getAt(i), this.getPath().getAt(i - 1));
}
if (dist < metres) {
return null;
}
var p1 = this.getPath().getAt(i - 2);
var p2 = this.getPath().getAt(i - 1);
var m = (metres - olddist) / (dist - olddist);
return new google.maps.LatLng(p1.lat() + (p2.lat() - p1.lat()) * m, p1.lng() + (p2.lng() - p1.lng()) * m);
}
}
/* 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>
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap&libraries=geometry">
</script>

Google maps api v3: geocoding multiple addresses (xml) and creating circles

I was able to get the code below working with a static radius number, but I'd like to pass the radius variable from the XML file to the circle. I tried using var rad = xmldata.getElementsByTagName('radius')[0].firstChild.data; but that didn't work. How do I do it?
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>Google Maps Multiple Markers</title>
<script src="http://maps.google.com/maps/api/js?sensor=false"
type="text/javascript"></script>
<script type="text/javascript" src="scripts/downloadxml.js"></script>
<script type="text/javascript">
var map = null;
var geocoder = new google.maps.Geocoder();
var info_window = new google.maps.InfoWindow();
var bounds = new google.maps.LatLngBounds();
function geocodeAddress(xmldata)
{
var address = xmldata.getElementsByTagName('address')[0].firstChild.data;
var city = xmldata.getElementsByTagName('city')[0].firstChild.data;
var address_google_map = address + ', ' + city + ', HI';
var info_text = address + '<br />' + city + ' HI';
geocoder.geocode
({'address': address_google_map},
function (results, status)
{
if (status == google.maps.GeocoderStatus.OK) {
createMarker(results[0].geometry.location, info_text);
} else {
alert("geocode of "+ address +" failed:"+status);
}
});
}
function createMarker(latlng, html)
{
var marker = new google.maps.Circle
({
**radius: 1000,**
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: "#0000FF",
fillOpacity: 0.35,
map: map,
center: latlng,
});
google.maps.event.addListener(marker, 'click', function() {
info_window.setContent(html);
info_window.open(map, marker);
});
bounds.extend(latlng); // Here we tell what are next viewport bounds
}
function initialize ()
{
var myLatLng = new google.maps.LatLng(21.3069,-157.8583);
var myOptions =
{
zoom: 10,
mapTypeControl: true,
center: myLatLng,
zoomControl: true,
zoomControlOptions:
{
style: google.maps.ZoomControlStyle.SMALL
},
StreetViewControl: false,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById('map'), myOptions);
google.maps.event.addListener
(map, 'click',
function ()
{
info_window.close();
});
downloadUrl('listings.xml',
function (listings_data)
{
listings_data = xmlParse(listings_data);
var markers = listings_data.documentElement.getElementsByTagName('listing');
var geocoder = new google.maps.Geocoder();
for (var i = 0; i < markers.length; i++)
{
geocodeAddress(markers[i]);
}
google.maps.event.addListenerOnce(map, 'idle', function() {map.fitBounds(bounds);});
});
}
</script>
</head>
<body onload="initialize();">
<div id="map" style="width:800px; height: 600px;"></div>
</body>
</html>
Here's the XML.
<?xml version="1.0" encoding="UTF-8"?>
<listings>
<listing>
<address>4123 Rideau Valley Rd</address>
<city>MANOTICK</city>
**<radius>10000</radius>**
</listing>
<listing>
<address>4456 Rideau Valley Rd</address>
<city>MANOTICK</city>
**<radius>20000</radius>**
</listing>
</listings>
Following the example of address and city :
var radius = xmldata.getElementsByTagName('radius')[0].firstChild.data;
then :
createMarker(results[0].geometry.location, info_text, radius);
and
function createMarker(latlng, html, radius) {
var marker = new google.maps.Circle({
radius: Number(radius),
...
});

Open InfoWindow for each polygon google maps V3

Hope someone can help me with this issue.
I'm trying to open an info windows on click for each polygon that my users created.
I used the same code for a marker and works well but i couldn't make it work for each polygon.
Any thoughts on how to solve this problem?
var contentString = '<div id="content">'+
'<div id="siteNotice">'+
'</div>'+
'<h2>Test</h2>'+
'</div>';
var infowindow = new google.maps.InfoWindow({
content: contentString
});
// Show Areas
<?php foreach ($field->result() as $f):?>
// Create an array with the coordanates of each area
var field<?=$f->id?>Coords = [
<?php $latlng=$this->resources_data->field_latlng($f->id);?>
<?php foreach ($latlng->result() as $point):?>
new google.maps.LatLng(<?=$point->lat?>, <?=$point->lng?>),
<?php endforeach;?>
];
// Create a polygon with the points of the area
var area<?=$f->id?>=new google.maps.Polygon({
paths: area<?=$f->id?>Coords,
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35
});
// Add the area to the map.
area<?=$f->id?>.setMap(map);
google.maps.event.addListener(area<?=$f->id?>,'click',function(){
infowindow.open(map,area<?=$f->id?>)
});
<?php endforeach;?>
You can't use the same form of InfoWindow.open for a polygon as you use for a marker (there is no marker to pass in).
From the documentation
open(map?:Map|StreetViewPanorama, anchor?:MVCObject)
Return Value: None
Opens this InfoWindow on the given map. Optionally, an InfoWindow can be associated with an anchor. In the core API, the only anchor is the Marker class. However, an anchor can be any MVCObject that exposes a LatLng position property and optionally a Point anchorPoint property for calculating the pixelOffset (see InfoWindowOptions). The anchorPoint is the offset from the anchor's position to the tip of the InfoWindow.)
You need to specifically set the place you want it to open when you call the open method (the latlng of the click is usually a good choice) with InfoWindow.setPosition().
Example
code snippet:
var infowindow = new google.maps.InfoWindow({
size: new google.maps.Size(150, 50)
});
function initialize() {
var geolib = google.maps.geometry.spherical;
var myOptions = {
zoom: 20,
center: new google.maps.LatLng(32.738158, -117.14874),
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
},
navigationControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
google.maps.event.addListener(map, 'click', function() {
infowindow.close();
});
bounds = new google.maps.LatLngBounds();
var polygon1 = new google.maps.Polygon({
map: map,
path: [geolib.computeOffset(new google.maps.LatLng(32.737355, -117.148719), 100, 0),
geolib.computeOffset(new google.maps.LatLng(32.737355, -117.148719), 100, 120),
geolib.computeOffset(new google.maps.LatLng(32.737355, -117.148719), 100, -120)
],
name: "polygon1"
});
google.maps.event.addListener(polygon1, 'click', function(event) {
var contentString = "name:" + this.name + "<br>" + event.latLng.toUrlValue(6);
infowindow.setContent(contentString);
infowindow.setPosition(event.latLng);
infowindow.open(map);
});
for (var i = 0; i < polygon1.getPath().getLength(); i++) {
bounds.extend(polygon1.getPath().getAt(i));
}
var polygon2 = new google.maps.Polygon({
map: map,
path: [geolib.computeOffset(new google.maps.LatLng(32.739341, -117.148912), 90, 180),
geolib.computeOffset(new google.maps.LatLng(32.739341, -117.148912), 90, 60),
geolib.computeOffset(new google.maps.LatLng(32.739341, -117.148912), 90, -60)
],
name: "polygon2"
});
google.maps.event.addListener(polygon2, 'click', function(event) {
var contentString = "name:" + this.name + "<br>" + event.latLng.toUrlValue(6);
infowindow.setContent(contentString);
infowindow.setPosition(event.latLng);
infowindow.open(map);
});
for (var i = 0; i < polygon2.getPath().getLength(); i++) {
bounds.extend(polygon2.getPath().getAt(i));
}
map.fitBounds(bounds);
}
google.maps.event.addDomListener(window, 'load', initialize);
function createClickablePoly(poly, html, label, point) {
gpolys.push(poly);
if (!point && poly.getPath && poly.getPath().getLength && (poly.getPath().getLength > 0) && poly.getPath().getAt(0)) {
point = poly.getPath().getAt(0);
}
var poly_num = gpolys.length - 1;
if (!html) {
html = "";
} else {
html += "<br>";
}
var length = poly.Distance();
if (length > 1000) {
html += "length=" + poly.Distance().toFixed(3) / 1000 + " km";
} else {
html += "length=" + poly.Distance().toFixed(3) + " meters";
}
for (var i = 0; i < poly.getPath().getLength(); i++) {
html += "<br>poly[" + poly_num + "][" + i + "]=" + poly.getPath().getAt(i);
}
html += "<br>Area: " + poly.Area() + " sq meters";
// html += poly.getLength().toFixed(2)+" m; "+(poly.getLength()*3.2808399).toFixed(2)+" ft; ";
// html += (poly.getLength()*0.000621371192).toFixed(2)+" miles";
var contentString = html;
google.maps.event.addListener(poly, 'click', function(event) {
infowindow.setContent(contentString);
if (event) {
point = event.latLng;
}
infowindow.setPosition(point);
infowindow.open(map);
// map.openInfoWindowHtml(point,html);
});
if (!label) {
label = "polyline #" + poly_num;
}
label = "<a href='javascript:google.maps.event.trigger(gpolys[" + poly_num + "],\"click\");'>" + label + "</a>";
// add a line to the sidebar html
// side_bar_html += '<input type="checkbox" id="poly'+poly_num+'" checked="checked" onclick="togglePoly('+poly_num+');">' + label + '<br />';
}
body,
html {
height: 100%;
width: 100%;
}
<script src="https://maps.google.com/maps/api/js?libraries=geometry&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<table border="1" style="height:100%; width:100%">
<tr>
<td>
<div id="map_canvas" style="width:100%; height:100%"></div>
</td>
<td width="200">
<div id="report"></div>
</td>
</tr>
</table>
<script>
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: {lat: 45.15492713361847, lng: 15.40557861328125}
});
var polygons = [{name: 'first name', coordinates:[{lat:45.15492713361847,lng:15.40557861328125},{lat:45.07933920973809,lng:15.5291748046875},{lat:45.01918507438175,lng:15.43304443359375},{lat:45.07933920973809,lng:15.3204345703125}]}];
// foreach your polygons
for (var i = 0; i < polygons.length; i++) {
var item = polygons[i];
var coors = item["coordinates"];
var name = item["name"];
var Polygon = new google.maps.Polygon({
path: coors,
strokeColor: '#66b3ff',
strokeOpacity: 0.8,
strokeWeight: 5,
editable: false,
fillColor: 'blue',
fillOpacity: 0.5,
});
Polygon.setMap(map);
// call function to set window
attachPolygonInfoWindow(Polygon, coors, name);
}
}
function attachPolygonInfoWindow(polygon, coors, html)
{
polygon.infoWindow = new google.maps.InfoWindow({
content: html
});
polygon.infoWindow.setPosition(getHighestWindowPosition(coors));
google.maps.event.addListener(polygon, 'mouseover', function () {
polygon.infoWindow.open(map, polygon);
});
google.maps.event.addListener(polygon, 'mouseout', function () {
polygon.infoWindow.close();
});
}
// function to get highest position of polygon to show window nice on top
function getHighestWindowPosition(coors) {
var lat = -5000, lng = 0, i = 0, n = coors.length;
for (; i !== n; ++i) {
if (coors[i].lat > lat) {
lat = coors[i].lat;
lng = coors[i].lng;
}
}
return {lat: lat, lng: lng};
}
</script>

google maps V3 polyline circle drawing, error: invalid value for constructor parameter 0

I am creating a map that allows a user to enter a zip code and a radius to be drawn around it. I am having a problem with google.maps.Polyline. The error message that I am receiving is "invalid value for constructor parameter 0.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0px; padding: 0px }
#map_canvas { height: 100% }
</style>
<script type="text/javascript"
src="http://maps.google.com/maps/api/js?sensor=false">
</script>
</script>
<script type= "text/javascript">
var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"),myOptions);
}
function codeAddress() {
var address = document.getElementById("address").value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
}
else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
function drawCircle() {
var address=document.getElementById("address").value;
var radius=document.getElementById("radius").value;
var latitude=40;
var longitude=0;
geocoder.geocode( { 'address': address}, function(results, status){
if (status==google.maps.GeocoderStatus.OK){
latlng=(results[0].geometry.location);
latitude=latlng.lat();
longitude=latlng.lng();
alert(latitude);
alert(longitude);
alert (radius);
}
else{
alert("Geocode was not successful for the following reason: " + status);
}
});
//Degrees to radians
var d2r = Math.PI / 180;
alert("calc d2r " + d2r);
// Radians to degrees
var r2d = 180 / Math.PI;
alert("calc r2d " + r2d);
// Earth radius is 3,963 miles
var cLat = (radius / 3963) * r2d;
alert("calc cLat " + cLat);
var cLng = cLat / Math.cos(latitude * d2r);
alert("calc cLng " + cLng);
//Store points in array
var points = [];
alert("declare array ");
// Calculate the points
// Work around 360 points on circle
for (var i=0; i < 360; i++) {
var theta = Math.PI * (i/16);
// Calculate next X point
circleX = longitude + (cLng * Math.cos(theta));
// Calculate next Y point
circleY = latitude + (cLat * Math.sin(theta));
// Add point to array
points.push(new google.maps.Point(circleX, circleY));
};
alert("completed loop");
var Polyline_Path = new google.maps.Polyline({
path: points,
strokeColor: "#003F87",
// color of the outline of the polyline
strokeOpacity: 1,
// between 0.0 and 1.0
strokeWeight: 5
// The stroke width in pixels
});
Polyline_Path.setMap(map);
//Add points to map
//var sColor="#003F87";
//alert("color");
//var stroke=.5;
//alert("stroke");
//map.addOverlay(new GPolyline(points, sColor, stroke));
//alert("added points to map");
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="width:500px; height:460px;
-moz-outline-radius:20px; -moz-box-sizing:padding-box; -moz-outline-style:solid ;-moz-outline-color:#9FB6CD;
-moz-outline-width:10px;"></div>
<div>
Zip Code: <input id="address" type="textbox" value="">
Radius:<input id="radius" type="textbox" value="">
<input type="button" value="Find" onclick="codeAddress() ">
<input type="button" value="Draw Radius" onclick= "drawCircle() ">
</div>
</body>
</html>
You are trying to create your Polyline (as your variable Polyline_Path) using an array of Point objects for the path property. However, the path property must be an array of LatLng objects.

google maps v3: clearing a circle made from polylines off the map

I am trying to figure out how to clear circles off the map that allows users to draw a radius around a point. My clearMap function doesn't seem to work. See code below
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0px; padding: 0px }
#map_canvas { height: 100% }
</style>
<script type="text/javascript"
src="http://maps.google.com/maps/api/js?sensor=false">
</script>
</script>
<script type= "text/javascript">
var geocoder;
var map;
var count=0;
//Store points in array
var points = [];
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions = {
zoom: 3,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"),myOptions);
}
function codeAddress() {
var address = document.getElementById("address").value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
}
else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
function plusCount(){
if (count==2){
count=0;
}
else{
count=count +1;
}
}
function drawCircle() {
var address=document.getElementById("address").value;
var radius=document.getElementById("radius").value;
var latitude=40;
var longitude=0;
geocoder.geocode( { 'address': address}, function(results, status){
if (status==google.maps.GeocoderStatus.OK){
latlng=(results[0].geometry.location);
latitude=latlng.lat();
longitude=latlng.lng();
alert(latitude);
alert(longitude);
alert (radius);
}
else{
alert("Geocode was not successful for the following reason: " + status);
}
});
//Degrees to radians
var d2r = Math.PI / 180;
alert("calc d2r " + d2r);
// Radians to degrees
var r2d = 180 / Math.PI;
alert("calc r2d " + r2d);
// Earth radius is 3,963 miles
var cLat = (radius / 3963) * r2d;
alert("calc cLat " + cLat);
var cLng = cLat / Math.cos(latitude * d2r);
alert("calc cLng " + cLng);
// Calculate the points
// Work around 360 points on circle
for (var i=0; i < 360; i++) {
var theta = Math.PI * (i/16);
// Calculate next X point
circleY = longitude + (cLng * Math.cos(theta));
// Calculate next Y point
circleX = latitude + (cLat * Math.sin(theta));
// Add point to array
points.push(new google.maps.LatLng(circleX, circleY));
};
alert("completed loop");
var colors=["#CD0000","#2E6444","#003F87" ];
var Polyline_Path = new google.maps.Polyline({
path: points,
strokeColor: colors[count],
// color of the outline of the polyline
strokeOpacity: 1,
// between 0.0 and 1.0
strokeWeight: 1,
// The stroke width in pixels
fillColor: colors[count],
fillOpacity: .5
});
Polyline_Path.setMap(map);
}
function clearMap(){
if(points){
for( i in points){
points[i].setMap(null);
}
points.length=0;
}}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="width:500px; height:460px;
-moz-outline-radius:20px; -moz-box-sizing:padding-box; -moz-outline- style:solid ;-moz-outline-color:#9FB6CD;
- moz-outline-width:10px;"></div>
<div>
Zip Code: <input id="address" type="textbox" value="">
Radius:<input id="radius" type="textbox" value="">
<input type="button" value="Find" onclick="codeAddress() ">
<input type="button" value="Draw Radius" onclick= "drawCircle() ; plusCount()">
<input type="button" value="Reset" onclick= "clearMap()">
</div>
</body>
If you create your circles using google.maps.Circle. Then you can create them and add tehm to an array like this
var options = {
strokeColor: #CD0000,
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: #2E6444,
fillOpacity: 0.5,
map: map,
center: latlng,
radius: parseInt(radius)
};
circles[circles.length] = new google.maps.Circle(options);
Then your clear map function will be
function clearMap(){
if (circles){
for (var idx=0;idx<circles.length;idx++){
circles[idx].setMap(null);
}
}
}

Resources