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

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);
}
}
}

Related

How to to Get Places (e.g Gas Stations) along Route Between Origin and Destination in Google Maps API

Can you please let me know if it is possible to get list of all places for example Gas Stations along Route Between Origin and Destination in Google Maps API? Here is a link that I am trying to list all Gas Stations or Rest areas ( or any of Google Maps API Supported Place Types)between two points ans based on a Direction supported route.
and this my code so far:
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
var haight = new google.maps.LatLng(49.216364,-122.811897);
var oceanBeach = new google.maps.LatLng(50.131446,-119.506838);
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var mapOptions = {
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: haight
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
directionsDisplay.setMap(map);
calcRoute();
}
function calcRoute() {
var request = {
origin: haight,
destination: oceanBeach,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
Edited Part:
// Make the directions request
directionService.route(request, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsRenderer.setDirections(result);
// Box around the overview path of the first route
var path = result.routes[0].overview_path;
var boxes = routeBoxer.box(path, distance);
drawBoxes(boxes);
} else {
alert("Directions query failed: " + status);
}
for (var i = 0; i < boxes.length; i++) {
var bounds = box[i];
// Perform search over this bounds
}
});
}
Use the RouteBoxer to get an array of google.maps.LatLngBounds objects that cover the route.
for each of those bounds use the Places library to search for the places.
Note that there are query limits and quotas on the places requests, so for long routes this may not be practical.
example
(however, looking at how the results are grouped, it looks like the places service is searching around the center of the bounds, rather than in the bounds, but it might be good enough for your needs).
code snippet:
var map = null;
var boxpolys = null;
var directions = null;
var routeBoxer = null;
var distance = null; // km
var service = null;
var gmarkers = [];
var boxes = null;
var infowindow = new google.maps.InfoWindow();
function initialize() {
// Default the map view to the continental U.S.
var mapOptions = {
center: new google.maps.LatLng(40, -80.5),
mapTypeId: google.maps.MapTypeId.ROADMAP,
zoom: 8
};
map = new google.maps.Map(document.getElementById("map"), mapOptions);
service = new google.maps.places.PlacesService(map);
routeBoxer = new RouteBoxer();
directionService = new google.maps.DirectionsService();
directionsRenderer = new google.maps.DirectionsRenderer({
map: map
});
// If there are any parameters at eh end of the URL, they will be in location.search
// looking something like "?marker=3"
// skip the first character, we are not interested in the "?"
var query = location.search.substring(1);
// split the rest at each "&" character to give a list of "argname=value" pairs
var pairs = query.split("&");
for (var i = 0; i < pairs.length; i++) {
// break each pair at the first "=" to obtain the argname and value
var pos = pairs[i].indexOf("=");
var argname = pairs[i].substring(0, pos).toLowerCase();
var value = pairs[i].substring(pos + 1).toLowerCase();
// process each possible argname - use unescape() if theres any chance of spaces
if (argname == "to") {
document.getElementById('to').value = unescape(value);
}
if (argname == "from") {
document.getElementById('from').value = unescape(value);
}
if (argname == "dist") {
document.getElementById('distance').value = parseFloat(value);
}
if (argname == "type") {
document.getElementById('type').value = unescape(value);
}
if (argname == "keyword") {
document.getElementById('keyword').value = unescape(value);
}
if (argname == "name") {
document.getElementById('name').value = unescape(value);
}
if (argname == "submit") {
route();
}
}
}
function route() {
// Clear any previous route boxes from the map
clearBoxes();
// Convert the distance to box around the route from miles to km
distance = parseFloat(document.getElementById("distance").value) * 1.609344;
var request = {
origin: document.getElementById("from").value,
destination: document.getElementById("to").value,
travelMode: google.maps.DirectionsTravelMode.DRIVING
}
// Make the directions request
directionService.route(request, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsRenderer.setDirections(result);
// Box around the overview path of the first route
var path = result.routes[0].overview_path;
boxes = routeBoxer.box(path, distance);
// alert(boxes.length);
drawBoxes();
findPlaces(0);
} else {
alert("Directions query failed: " + status);
}
});
}
// Draw the array of boxes as polylines on the map
function drawBoxes() {
boxpolys = new Array(boxes.length);
for (var i = 0; i < boxes.length; i++) {
boxpolys[i] = new google.maps.Rectangle({
bounds: boxes[i],
fillOpacity: 0,
strokeOpacity: 1.0,
strokeColor: '#000000',
strokeWeight: 1,
map: map
});
}
}
function findPlaces(searchIndex) {
var type = document.getElementById('type').value;
var keyword = document.getElementById('keyword').value;
var name = document.getElementById('name').value;
var request = {
bounds: boxes[searchIndex],
};
if (!!type && (type != "")) {
if (type.indexOf(',') > 0)
request.types = type.split(',');
else
request.types = [type];
}
if (!!keyword && (keyword != "")) request.keyword = keyword;
if (!!name && (name != "")) request.name = name;
service.nearbySearch(request, function(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
document.getElementById('side_bar').innerHTML += "bounds[" + searchIndex + "] returns " + results.length + " results<br>"
for (var i = 0, result; result = results[i]; i++) {
var marker = createMarker(result);
}
} else {
document.getElementById('side_bar').innerHTML += "bounds[" + searchIndex + "] returns 0 results<br> status=" + status + "<br>";
}
if (status != google.maps.places.PlacesServiceStatus.OVER_QUERY_LIMIT) {
searchIndex++;
if (searchIndex < boxes.length)
findPlaces(searchIndex);
} else { // delay 1 second and try again
setTimeout("findPlaces(" + searchIndex + ")", 1000);
}
});
}
// Clear boxes currently on the map
function clearBoxes() {
if (boxpolys != null) {
for (var i = 0; i < boxpolys.length; i++) {
boxpolys[i].setMap(null);
}
}
boxpolys = null;
}
function createMarker(place) {
var placeLoc = place.geometry.location;
if (place.icon) {
var image = new google.maps.MarkerImage(
place.icon, new google.maps.Size(71, 71),
new google.maps.Point(0, 0), new google.maps.Point(17, 34),
new google.maps.Size(25, 25));
} else var image = {
url: "https://maps.gstatic.com/intl/en_us/mapfiles/markers2/measle.png",
size: new google.maps.Size(7, 7),
anchor: new google.maps.Point(3.5, 3.5)
};
var marker = new google.maps.Marker({
map: map,
icon: image,
position: place.geometry.location
});
var request = {
reference: place.reference
};
google.maps.event.addListener(marker, 'click', function() {
service.getDetails(request, function(place, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
var contentStr = '<h5>' + place.name + '</h5><p>' + place.formatted_address;
if (!!place.formatted_phone_number) contentStr += '<br>' + place.formatted_phone_number;
if (!!place.website) contentStr += '<br><a target="_blank" href="' + place.website + '">' + place.website + '</a>';
contentStr += '<br>' + place.types + '</p>';
infowindow.setContent(contentStr);
infowindow.open(map, marker);
} else {
var contentStr = "<h5>No Result, status=" + status + "</h5>";
infowindow.setContent(contentStr);
infowindow.open(map, marker);
}
});
});
gmarkers.push(marker);
if (!place.name) place.name = "result " + gmarkers.length;
var side_bar_html = "<a href='javascript:google.maps.event.trigger(gmarkers[" + parseInt(gmarkers.length - 1) + "],\"click\");'>" + place.name + "</a><br>";
document.getElementById('side_bar').innerHTML += side_bar_html;
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map_canvas {
margin: 0;
padding: 0;
height: 100%;
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=places&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<script src="https://cdn.jsdelivr.net/gh/denissellu/routeboxer#master/src/RouteBoxer.js" type="text/javascript"></script>
<table border="1">
<tr>
<td valign="top">
<div id="map" style="width: 600px; height: 500px;"></div>
</td>
<td>
<div id="side_bar" style="width:200px; height: 600px; overflow: auto"></div>
</td>
</tr>
</table>
Box within at least
<input type="text" id="distance" value="3" size="2">miles of the route from
<input type="text" id="from" value="denver" />to
<input type="text" id="to" value="oklahoma city, OK" />
<input type="submit" onclick="route()" />
<br>
<label>type</label>
<input type="text" id="type" value="gas_station" />
<label>keyword</label>
<input type="text" id="keyword" value="" />
<label>name</label>
<input type="text" id="name" value="" />
<div id="towns"></div>

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 fill in circle completely

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');
}
});
}

Resources