How can I divide a circle into sectors on Google Maps?

Is there a way to divide a circle in Google Maps into sectors of 120 degrees? Currently, I am able to draw a simple circle with a radius that looks like this:

map = new google.maps.Map(document.getElementById('map_canvas'), {
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    zoom: 16,
    center: new google.maps.LatLng(55.685025, 21.118995)
});

var lat_lng = new google.maps.LatLng(55.685025, 21.118995);

marker = new google.maps.Marker({
    position: lat_lng,
    map: map,
    icon: 'map_green.png'
});

circle = new google.maps.Circle({
    map: map,
    radius: 200,
    fillColor: 'green',
    center: lat_lng
});

My next step is to draw three polygons on top of the circle, but I'm unsure how to calculate their positions...

The desired result should resemble this:

Answer №1

Here's an alternative method using the google.maps.geometry library, make sure to include the 'libraries=geometry' parameter in the google maps script src:

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>Some Title</title>
... (omitted for brevity) ...
google.maps.event.addDomListener(window, 'load', initialize);

</script>
</body>
</html>

View the live example: http://jsfiddle.net/rkC2S/

Answer №2

If you're looking for a way to achieve this, consider referring to this particular example

function createArc(center, initialBearing, finalBearing, radius) { 
var d2r = Math.PI / 180;   
var r2d = 180 / Math.PI;   

   var points = 32; 

   // calculating the radius in lat/lon 
   var rlat = (radius / EarthRadiusMeters) * r2d; 
   var rlng = rlat / Math.cos(center.lat() * d2r); 

   var extPoints = new Array();

   if (initialBearing > finalBearing) finalBearing += 360;
   var deltaBearing = finalBearing - initialBearing;
   deltaBearing = deltaBearing/points;

   for (var i=0; (i < points+1); i++) 
   { 
      extPoints.push(center.DestinationPoint(initialBearing + i*deltaBearing, radius)); 
      bounds.extend(extPoints[extPoints.length-1]);
   } 
   return extPoints;
}

  var arcCoordinates = createArc(centerPoint, centerPoint.Bearing(startPoint), centerPoint.Bearing(endPoint), centerPoint.distanceFrom(startPoint), -1.0);
  
  arcCoordinates.push(centerPoint);
  bounds.extend(centerPoint);
  arcCoordinates.push(startPoint);

  var piePolygon = new google.maps.Polygon({
                 paths: [arcCoordinates],
                 strokeColor: "#00FF00",
                 strokeOpacity: 0.5,
                 strokeWeight: 2,
                 fillColor: "#FF0000",
                 fillOpacity: 0.35,
                 map: map
     })

This was implemented prior to the availability of the geometry library, so some functionality may differ compared to what is available now.

For an example that utilizes the geometry library

// Source: http://en.wikipedia.org/wiki/Earth_radius
/*
/ Equatorial radius
/ The Earth's equatorial radius a, or semi-major axis, is the distance from its center to the equator and equals 6,378.1370 km (?3,963.191 mi; ?3,443.918 nmi).
*/
var EarthRadiusMeters = 6378137.0; // meters

google.maps.LatLng.prototype.DestinationPoint = function (brng, dist) {
var R = EarthRadiusMeters; 
var brng = brng.toRad();
var lat1 = this.lat().toRad(), lon1 = this.lng().toRad();
var lat2 = Math.asin( Math.sin(lat1)*Math.cos(dist/R) + 
                      Math.cos(lat1)*Math.sin(dist/R)*Math.cos(brng) );
var lon2 = lon1 + Math.atan2(Math.sin(brng)*Math.sin(dist/R)*Math.cos(lat1), 
                             Math.cos(dist/R)-Math.sin(lat1)*Math.sin(lat2));

return new google.maps.LatLng(lat2.toDeg(), lon2.toDeg());
}

google.maps.LatLng.prototype.Bearing = function(otherLatLng) {
  var from = this;
  var to = otherLatLng;
  if (from.equals(to)) {
    return 0;
  }
  var lat1 = from.latRadians();
  var lon1 = from.lngRadians();
  var lat2 = to.latRadians();
  var lon2 = to.lngRadians();
  var angle = - Math.atan2( Math.sin( lon1 - lon2 ) * Math.cos( lat2 ), Math.cos( lat1 ) * Math.sin( lat2 ) - Math.sin( lat1 ) * Math.cos( lat2 ) * Math.cos( lon1 - lon2 ) );
  if ( angle < 0.0 ) angle  += Math.PI * 2.0;
  if ( angle > Math.PI ) angle -= Math.PI * 2.0; 
  return parseFloat(angle.toDeg());
}

Number.prototype.toRad = function () {
  return this * Math.PI / 180;
};

Number.prototype.toDeg = function () {
  return this * 180 / Math.PI;
};

Number.prototype.toBrng = function () {
  return (this.toDeg() + 360) % 360;
};

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Node.js allows for downloading files from an FTP server to a client easily

System architecture The system is composed of 3 main components: 1: FTP server: Exclusively used for file storage, accessible only through the Node.js app. No direct access permitted. 2: Node.js: Acts as an API to interact with the FTP server. It is the ...

The Next.js React application fails to load the updated page when clicking on a Link

I am currently working with Next.js version 14, utilizing the App router and the Link component from Next.js's next/link. In my file structure, within folder app/a, there are: page.tsx which fetches data from an API and passes it to the <Table/> ...

What is the best way to pass the setState value to the useEffect hook?

After watching a Youtube video, I took on the challenge of creating my own recipe app using React.js as a beginner. I have been troubleshooting for the past 2 days and seem to have hit a roadblock. The issue lies in passing the value of my state to the use ...

What could be causing my issue with the if-else condition not functioning properly?

Why does the code only work for adding and removing styles in Part (else), but not returning the class when clicked again? var navDropDown = document.querySelectorAll('.menu-item-has-children > a'); for (let i = 0; i < navDropDown.length; i ...

What is the best way to modify the background of my li element when it is clicked on?

I stumbled upon this article: Modifying Li Element Colors in HTML <ul> Using onclick Event It seems to address what I need, but I'm a little unsure of how to implement something similar in a rails app that also utilizes react/redux. Most of the ...

What could possibly be the reason for the malfunctioning light in this particular setting?

Recently, I developed a game class using Coffeescript that showcases both a static and rotating cube. If you are interested in checking out the code, you can find it here: http://jsfiddle.net/6eRzt/6/ Despite everything working smoothly, there are two iss ...

What's the significance of & in TypeScript and JavaScript?

While exploring someone else's code, I came across this interesting piece related to the props of a React component. Although I'm aware that & is typically used as an AND logical operator, it seems to have a different significance in this con ...

Unable to view the image in browsers other than Internet Explorer

On a webpage, there is a feature where clicking on the "Add More" link should display an input box and a "Delete" button image. Surprisingly, this functionality works perfectly on IE browsers, but not on Mozilla or Chrome. In non-IE browsers, only the text ...

What is the best way to modify an object property that is nested within a userContext?

Is it possible to update a specific property in useContext? export const AuthContext = createContext(); const { obra, setObra } = useContext(AuthContext); setObra(...obra, ...obra.nome_equipe_01 = e.target.value); I am looking to modify the 'nome_equ ...

Table that is sized to fit perfectly within the entire width of the viewport

In my current project, I am developing a reporting feature that allows users to select various elements to include in their report. The number of elements available can change based on the user's preferences, and each element may contain user-generate ...

Having difficulty with delaying the loading of a div layer and javascript after the page has initially loaded

I've been struggling to make this script wait a few seconds after the page has loaded, but I haven't been successful so far. Despite trying some solutions from similar questions here, nothing seems to be working. Any help you can provide would b ...

Discrepancy in sorting order of key-value objects in JavaScript

Check out my jsFiddle demonstration illustrating the issue: Example Here is the HTML structure: <select id="drop1" data-jsdrop-data="countries"></select> <select id="drop2" data-jsdrop-data="countries2"></select>​ Below is the ...

The error message received is: "TypeError: Unable to serialize method object to JSON."

Every time I click on the like button, an internal server error shows up in the console. The issue lies in returning a HttpResponse from the view function. How can I properly return a value in HttpResponse so that I can access it in JavaScript? Console e ...

Attempting to develop a kick command for discord using discord.js, which will initiate the kick action based on the user's

I've been trying to implement a discord kick command that specifically targets a user on my server. It may not be the most practical solution, but it's essential for my bot's functionality. Here's the code I have so far: if (command == ...

What is the best way to retrieve a date from MySQL that is exactly 30 days ahead of today using PHP

My coding skills are lacking, so here is my current code (retrieve date from mysql = today --> alert) and I'm seeking assistance to modify it to (retrieve date from mysql + 30 days = today --> alert) <?php $check=mysql ...

Unforeseen behavior in event binding causing knockout knockout

I implemented an event binding for the scroll event on a DIV. To add debounce functionality to the handler, I created a function on my model that generates the debounced handler. Then, in my view, I bind this factory function. I assumed that my factory fu ...

Adjusting the value of 'let' based on the outcome

Can you assist me with this issue? I am attempting to assign a value to a let variable based on the following if conditional block. class Main extends React.Component{ render(){ let content = ''; firebase.auth().onAuthStateChanged(func ...

Utilizing HTML5 to automatically refresh the page upon a change in geolocation

I have a web application built with AngularJS. One of the functionalities is activated only when the user is in close proximity to specific locations. To make this work, I can constantly refresh the page every 5 seconds and carry out calculations to dete ...

Displaying elements of an array object using Javascript

I am currently working on counting the frequency of elements in an array using a for loop with arrays of objects. The code prints the correct output. counts = {}; counter = 0; counter_array = [50,50,0,200]; //this example array is dynamically filled for ...

Adding custom methods to an Angular $resource to enhance prototypal functionality

Seeking a way to retrieve objects from a server, similar to this: var User = $resource('/user/:userId', {userId:'@id'}); I desire all User instances to possess specific methods for computing derived data without requiring the server t ...