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>
Related
Like title says - I want to avoid map zooming after rendering directions.
I found here a lot of about it, for example Do not change map center or zoom level when rendering directions, but after adding {preserveViewport: true} to DirectionsRenderer nothing happens.
I don't want to calculate the union of the bounds of the directions responses, but only 'freeze' while rendering directions. What am I doing wrong?
My map: https://jsfiddle.net/harlowpl/xawy71r0/33/
infoWindow = new google.maps.InfoWindow();
directionsService = new google.maps.DirectionsService();
directionsDisplay = new google.maps.DirectionsRenderer({
map: map,
preserveViewport: true,
markerOptions: {
visible: false
}
});
createSourceMarker();
createDestinationMarkers();
}
function markerClicked(destinationLocation) {
var directionsRequest = {
origin: sourceLocation,
destination: destinationLocation,
travelMode: 'DRIVING'
};
directionsService.route(directionsRequest, handleDirectionResults);
}
function handleDirectionResults(result, status) {
if (status === 'OK') {
directionsDisplay.setDirections(result);
} else {
console.log(status);
}
}
}
});
You have the zoom level set to a non-integer value. It is changing to an integer value when the directions result is displayed.
Hidden away in the documentation, it says: Specify zoom level as an integer.
proof of concept fiddle (setting zoom to 16, rather than 15.5)
code snippet:
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px;
}
<div id="map"></div>
<script>
var sourceLocation = {
lat: 52.340822,
lng: 16.855841
};
var destinationLocations = [{
lat: 52.344583,
lng: 16.849864
},
{
lat: 52.343319,
lng: 16.855080
},
];
var directionsService;
var directionsDisplay;
var infoWindow;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: 52.343580,
lng: 16.857495
},
zoom: 16,
styles: [{
"featureType": "poi",
"elementType": "all",
"stylers": [{
"visibility": "off"
}]
}],
gestureHandling: 'cooperative'
});
// console.log("zoom=" + map.getZoom());
// console.log("zoom=" + map.getZoom()+" bounds="+map.getBounds().toUrlValue());
google.maps.event.addListener(map, 'zoom_changed', function() {
console.log("zoom=" + map.getZoom());
});
google.maps.event.addListener(map, 'bounds_changed', function() {
console.log("zoom=" + map.getZoom() + " bounds=" + map.getBounds().toUrlValue());
});
infoWindow = new google.maps.InfoWindow();
directionsService = new google.maps.DirectionsService();
directionsDisplay = new google.maps.DirectionsRenderer({
map: map,
preserveViewport: true,
markerOptions: {
visible: false
}
});
createSourceMarker();
createDestinationMarkers();
}
function markerClicked(destinationLocation) {
var directionsRequest = {
origin: sourceLocation,
destination: destinationLocation,
travelMode: 'DRIVING'
};
directionsService.route(directionsRequest, handleDirectionResults);
}
function handleDirectionResults(result, status) {
if (status === 'OK') {
directionsDisplay.setDirections(result);
} else {
console.log(status);
}
}
function createSourceMarker() {
new google.maps.Marker({
position: sourceLocation,
map: map,
icon: 'http://nakujawskiej.pl/nk/wp-content/uploads/mapMarkers/marker-main.svg'
});
}
var opis = [
'<div id="content">' +
'<div id="siteNotice">' +
'</div>' +
'<center><h4 id="firstHeading" class="firstHeading">Apteka</h4></center>' + '<hr>' +
'<div id="bodyContent">' +
'<p><b>Odległość :</b>' + ' 750m' + '<br>' + '<b>Czas dojazdu :</b>' + ' 2 min</p>' +
'</div>' +
'</div>',
'<div id="content">' +
'<div id="siteNotice">' +
'</div>' +
'<h4 id="firstHeading" class="firstHeading">Przedszkole</h4>' + '<hr>' +
'<div id="bodyContent">' +
'<p><b>Odległość :</b>' + ' 450m' + '<br>' + '<br>' + '<b>Czas dojazdu :</b>' + ' 2 min</p>' +
'</div>' +
'</div>',
];
var opisIndex = 0;
var iconBase = 'http://nakujawskiej.pl/nk/wp-content/uploads/mapMarkers/';
var markers = [
iconBase + 'marker-01.svg',
iconBase + 'marker-02.svg'
];
var markersIndex = 0;
function createDestinationMarkers() {
destinationLocations.forEach(function(location, index) {
var opisIndex = markersIndex;
var marker = new google.maps.Marker({
position: location,
map: map,
icon: markers[markersIndex++ % markers.length],
});
marker.addListener('click', function() {
infoWindow.setContent(opis[opisIndex % opis.length]);
infoWindow.open(map, marker);
});
marker.addListener('click', function() {
markerClicked(location);
});
})
}
// google.maps.event.addDomListener(window, "load", initMap);
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDo5rkrpNDFQnr5Afq9fKGmGjOTPC0C390&callback=initMap" async defer></script>
I created a polygon on google map and would like a infoWindow to pop up when I click on the polygon. Code as the follows:
google.maps.event.addListener(polygon, 'click', showVolume);
polygon_infoWindow = new google.maps.InfoWindow;
In the showVolume function,
function showVolume(event){
var polygon_Name = this.Name;
var volume = this.Volume;
var pt = event.latlng;
var contentString = '<b>Name: </b>' + polygon_Name + '<br>' + '<b>Volume: </b>' + volume + '<br>' + '<b>Clicked Location: </b>' + pt;
polygon_infoWindow.setContent(contentString);
polygon_infoWindow.open(map);
polygon_infoWindow.setPosition(pt);
}
The function returned the correct information belonging to the polygon. However it returned the event.latlng as undefined. I wonder what is wrong.
event.latlng doesn't exist, javascript is case sensitive, the property is event.latLng
proof of concept fiddle
code snippet:
var geocoder;
var map;
var polygon_infoWindow;
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
});
var polygon = new google.maps.Polygon({
map: map,
Name: "Fred",
Volume: 1000,
path: [{
lat: 37.4419,
lng: -122.1419
}, {
lat: 37.42,
lng: -122.16
}, {
lat: 37.4419,
lng: -122.1819
}]
});
google.maps.event.addListener(polygon, 'click', showVolume);
polygon_infoWindow = new google.maps.InfoWindow;
}
google.maps.event.addDomListener(window, "load", initialize);
function showVolume(event) {
var polygon_Name = this.Name;
var volume = this.Volume;
var pt = event.latLng;
var contentString = '<b>Name: </b>' + polygon_Name + '<br>' + '<b>Volume: </b>' + volume + '<br>' + '<b>Clicked Location: </b>' + pt;
polygon_infoWindow.setContent(contentString);
polygon_infoWindow.setPosition(pt);
polygon_infoWindow.open(map);
}
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>
I have retrieved the data from xml..Generated Sidebar. I want to open infowindow on click on the sidebar.. Tried so many examples and codes but not succeeded... Can you please suggest what should be function declaration for myclick function:
Below i am mentioning my code...I will be grateful to you if any one can help!!
var gmarkers = [];
function load() {
var side_bar_html = "<div class=\"pro_curved-hz-2\"><div class=\"pro_text-shadow\" style=\"height: 250px;overflow-x:hidden;overflow-y: scroll;\">";
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(<?php echo $SelectedLatitude; ?>,<?php echo $SelectedLongitude; ?>),
zoom: <?php echo $Zoom; ?>,
mapTypeId: 'roadmap'
});
var infoWindow = new google.maps.InfoWindow;
// Change this depending on the name of your PHP file
downloadUrl("/map.php", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
var count=markers.length;
if(count>0)
side_bar_html += '<span class=\"pro_info pro_info-indent pro_info_success\">' + count + ' result found!! </span><div class=clear></div>';
else
side_bar_html += '<span class=\"pro_info pro_info-indent pro_info_warning\"> No Result found!! </span><div class=clear></div>';
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("name");
var address = markers[i].getAttribute("address");
var type = markers[i].getAttribute("type");
var link= '/Place';
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var html = "<b>" + name + "</b> <br/>" + address;
var Mainicon = customMainIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: Mainicon.icon,
shadow: Mainicon.shadow,
animation: google.maps.Animation.DROP,
});
gmarkers[i] = marker;
side_bar_html += '<div class=\"pro_curved-hz-2-1\" onclick="myclick('+i+');" onmouseover="mymouseover('+i+');" onmouseout="mymouseout('+i+');" ><div class=\"pro_text-shadow\"><a href=' + link + '>' + name + '</a><br>' + address + '</div></div>';
bindInfoWindow(marker, map, infoWindow, html, side_bar_html);
}
side_bar_html += "</div></div>";
});
}
function myclick(index) {
}
function mymouseover(i) {
gmarkers[i].setAnimation(google.maps.Animation.BOUNCE);
}
function mymouseout(i) {
gmarkers[i].setAnimation(null);
}
function bindInfoWindow(marker, map, infoWindow, html, side_bar_html) {
document.getElementById("SideBar").innerHTML = side_bar_html;
google.maps.event.addListener(marker,'mouseover', function() {
//marker.setAnimation(google.maps.Animation.BOUNCE);
//setTimeout(function(){ marker.setAnimation(null); }, 750);
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
google.maps.event.addListener(marker,'mouseout', function() {
infoWindow.setContent(html);
infoWindow.close(map, marker);
});
var p=<?php echo $Zoom; ?>;
google.maps.event.addListener(marker, 'click', function() {
p+=1;
if(p>=20)
{
infoWindow.setContent(html);
infoWindow.open(map, marker);
}
else
{
map.setZoom(p);
map.setCenter(marker.getPosition());
}
});
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
//]]>
Here is an example that does what you are requesting (with function closure and a createMarker function).
Here is an example that doesn't use function closure.
Hi the below code gives the place search , but it is showing only names i want the complete details of the places in the infobox..the below code isprovided by DR.Molle
http://jsfiddle.net/doktormolle/C5ZtK/
below is the code for retrieving the placedetails but not able to make it working
var request = { reference: place.reference };
service.getDetails(request, function(details, status) {
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(details.name + "<br />" + details.formatted_address +"<br />" + details.website + "<br />" + details.rating + "<br />" + details.formatted_phone_number);
infowindow.open(map, this);
});
});
}
i checked the developers page but not able to get much from it Any help would be appreciated
Example that gets the place details for the clicked marker:
http://www.geocodezip.com/v3_GoogleEx_place-search_starbucks3.html
code snippet:
var geocoder = null;
var map;
var service;
var infowindow;
var gmarkers = [];
var bounds = null;
function initialize() {
geocoder = new google.maps.Geocoder();
var pyrmont = new google.maps.LatLng(-33.8665433, 151.1956316);
map = new google.maps.Map(document.getElementById('map'), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: pyrmont,
zoom: 15
});
geocoder.geocode({
'address': "Seattle, WA"
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var point = results[0].geometry.location;
bounds = results[0].geometry.viewport;
var rectangle = new google.maps.Rectangle({
bounds: bounds,
fillColor: "#FF0000",
fillOpacity: 0.4,
strokeColor: "#0000FF",
strokeWeigth: 2,
strokeOpacity: 0.9,
map: map
});
map.fitBounds(bounds);
var request = {
bounds: bounds,
name: "starbucks",
types: ['establishment']
};
infowindow = new google.maps.InfoWindow();
service = new google.maps.places.PlacesService(map);
service.search(request, callback);
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
}
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
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);
}
});
});
gmarkers.push(marker);
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;
}
function openInfoWindow(id) {
return true;
}
google.maps.event.addDomListener(window, 'load', initialize);
#map {
height: 400px;
width: 600px;
border: 1px solid #333;
margin-top: 0.6em;
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>
<table border="1">
<tr>
<td>
<div id="map"></div>
</td>
<td>
<div id="side_bar"></div>
</td>
</tr>
</table>
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');
}
});
}