Google maps Custom marker - svg - google-maps

I'm trying to add custom marker - SVG of donut shape. Following is the link of fiddle :
https://jsfiddle.net/jfx2uqws/7/
Code:
let map;
let latlng_statue = new google.maps.LatLng(-33.92, 151.25);
function initialize() {
var mapOptions = {
zoom: 17,
center: latlng_statue
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
let data = [{
fill:25,
color:"#80e080"
},{
fill:25,
color:"#4fc3f7"
},{
fill:25,
color:"#9575cd"
},{
fill:25,
color:"#f06292"
}]
let doughnut = document.querySelector("#map-canvas"),
svg = document.createElementNS("http://www.w3.org/2000/svg", "svg"),
filled = 0;
svg.setAttribute("width","80px");
svg.setAttribute("height","80px");
svg.setAttribute("viewBox","0 0 100 100");
doughnut.appendChild(svg);
data.forEach(function(o,i){
var circle = document.createElementNS("http://www.w3.org/2000/svg","circle"),
startAngle = -90,
radius = 30,
cx = 50,
cy = 50,
strokeWidth = 15,
dashArray = 2*Math.PI*radius,
dashOffset = dashArray - (dashArray * o.fill / 100),
angle = (filled * 360 / 100) + startAngle;
circle.setAttribute("r",radius);
circle.setAttribute("cx",cx);
circle.setAttribute("cy",cy);
circle.setAttribute("fill","transparent");
circle.setAttribute("stroke",o.color);
circle.setAttribute("stroke-width",strokeWidth);
circle.setAttribute("stroke-dasharray",dashArray);
circle.setAttribute("stroke-dashoffset",dashOffset);
circle.setAttribute("transform","rotate("+(angle)+" "+cx+" "+cy+")");
svg.appendChild(circle);
filled+= o.fill;
})
var foreignobject = document.createElementNS("http://www.w3.org/2000/svg","foreignobject"),
clsName="node",
x="40",
y="42",
width="20",
height="20";
foreignobject.setAttribute("class",clsName);
foreignobject.setAttribute("x",x);
foreignobject.setAttribute("y",y);
foreignobject.setAttribute("width",20);
foreignobject.setAttribute("height",20);
let spanEl = document.createElement("span");
spanEl.setAttribute("style", "font-size: 10px;");
let fontColor = document.createElement("font");
fontColor.setAttribute("style", "color: red;");
let iconEl = document.createElement("i");
iconEl.setAttribute("class","fa fa-cloud");
fontColor.appendChild(iconEl);
spanEl.appendChild(fontColor);
foreignobject.appendChild(spanEl);
svg.appendChild(foreignobject);
let s = new XMLSerializer();
let str = s.serializeToString(svg);
let marker = new google.maps.Marker({
position: latlng_statue,
map: map,
title: 'donut',
icon: { url: 'data:image/svg+xml;charset=UTF-8,' + encodeURIComponent(str), scaledSize: new google.maps.Size(50, 50) },
optimized: false
});
}
google.maps.event.addDomListener(window, 'load', initialize);
Problem is - I'm trying to add icon in the middle of the donut. But its not getting displayed.
So, looking for the solution or if any other easy way to achieve the above thing - svg multi color donut with icon in between.

Related

How to add Multiple Polylines using Google Map JS Api while using addListeners

I am trying to add multiple polylines to the following sample and if i do so it is drawing the latest polyline and removing the old one. I know it can be done while loading the map. I have to use the following logic as it is perfectly drawing the arc between markers.
var map;
var curvature = 0.5; // how curvy to make the arc
function init() {
var Map = google.maps.Map,
LatLng = google.maps.LatLng,
LatLngBounds = google.maps.LatLngBounds,
Marker = google.maps.Marker,
Point = google.maps.Point;
// This is the initial location of the points
// (you can drag the markers around after the map loads)
var pos1 = new LatLng(38.60971599083999, -105.42822913560047);
var pos2 = new LatLng(31.549917555822212, -99.49938531446615);
var bounds = new LatLngBounds();
bounds.extend(pos1);
bounds.extend(pos2);
map = new Map(document.getElementById('map-canvas'), {
center: bounds.getCenter(),
zoom: 12
});
map.fitBounds(bounds);
var markerP1 = new Marker({
position: pos1,
// draggable: true,
map: map
});
var markerP2 = new Marker({
position: pos2,
// draggable: true,
map: map
});
var curveMarker;
function updateCurveMarker() {
var pos1 = markerP1.getPosition(), // latlng
pos2 = markerP2.getPosition(),
projection = map.getProjection(),
p1 = projection.fromLatLngToPoint(pos1), // xy
p2 = projection.fromLatLngToPoint(pos2);
// Calculate the arc.
// To simplify the math, these points
// are all relative to p1:
var e = new Point(p2.x - p1.x, p2.y - p1.y), // endpoint (p2 relative to p1)
m = new Point(e.x / 2, e.y / 2), // midpoint
o = new Point(e.y, -e.x), // orthogonal
c = new Point( // curve control point
m.x + curvature * o.x,
m.y + curvature * o.y);
var pathDef = 'M 0,0 ' +
'q ' + c.x + ',' + c.y + ' ' + e.x + ',' + e.y;
var zoom = map.getZoom(),
scale = 1 / (Math.pow(2, -zoom));
var symbol = {
path: pathDef,
scale: scale,
strokeWeight: 1,
fillColor: 'none'
};
if (!curveMarker) {
curveMarker = new Marker({
position: pos1,
clickable: false,
icon: symbol,
zIndex: 0, // behind the other markers
map: map
});
} else {
curveMarker.setOptions({
position: pos1,
icon: symbol,
});
}
}
google.maps.event.addListener(map, 'projection_changed', updateCurveMarker);
google.maps.event.addListener(map, 'zoom_changed', updateCurveMarker);
}
google.maps.event.addDomListener(window, 'load', init);
html, body, #map-canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?sensor=false&libraries=geometry,places&key=YOUR_API_KEY"></script>
<div id="map-canvas" style="border: 2px solid #3872ac;"></div>
How to add multiple polylines by adapting to the curve logic above?
Encapsulate the functionality to make the curve in a function and call it for every curve you want to appear on the map:
function createCurveMarker(marker1, marker2, map) {
var curveMarker;
function updateCurveMarker() {
var pos1 = marker1.getPosition(), // latlng
pos2 = marker2.getPosition(),
projection = map.getProjection(),
p1 = projection.fromLatLngToPoint(pos1), // xy
p2 = projection.fromLatLngToPoint(pos2);
// Calculate the arc.
// To simplify the math, these points
// are all relative to p1:
var e = new google.maps.Point(p2.x - p1.x, p2.y - p1.y), // endpoint (p2 relative to p1)
m = new google.maps.Point(e.x / 2, e.y / 2), // midpoint
o = new google.maps.Point(e.y, -e.x), // orthogonal
c = new google.maps.Point( // curve control point
m.x + curvature * o.x,
m.y + curvature * o.y);
var pathDef = 'M 0,0 ' +
'q ' + c.x + ',' + c.y + ' ' + e.x + ',' + e.y;
var zoom = map.getZoom(),
scale = 1 / (Math.pow(2, -zoom));
var symbol = {
path: pathDef,
scale: scale,
strokeWeight: 1,
fillColor: 'none'
};
if (!curveMarker) {
curveMarker = new google.maps.Marker({
position: pos1,
clickable: false,
icon: symbol,
zIndex: 0, // behind the other markers
map: map
});
} else {
curveMarker.setOptions({
position: pos1,
icon: symbol,
});
}
}
google.maps.event.addListener(map, 'projection_changed', updateCurveMarker);
google.maps.event.addListener(map, 'zoom_changed', updateCurveMarker);
}
working code snippet:
var map;
var curvature = 0.5; // how curvy to make the arc
function init() {
// This is the initial location of the points
// (you can drag the markers around after the map loads)
var pos1 = new google.maps.LatLng(38.60971599083999, -105.42822913560047);
var pos2 = new google.maps.LatLng(31.549917555822212, -99.49938531446615);
var bounds = new google.maps.LatLngBounds();
bounds.extend(pos1);
bounds.extend(pos2);
map = new google.maps.Map(document.getElementById('map-canvas'), {
center: bounds.getCenter(),
zoom: 12
});
var markerP1 = new google.maps.Marker({
position: pos1,
zIndex: 10,
map: map
});
var markerP2 = new google.maps.Marker({
position: pos2,
zIndex: 10,
map: map
});
createCurveMarker(markerP1, markerP2, map);
var pos3 = new google.maps.LatLng(43.8041334, -120.5542012);
var pos4 = new google.maps.LatLng(38.8026097, -116.419389);
bounds.extend(pos3);
bounds.extend(pos4);
map.fitBounds(bounds);
var markerP3 = new google.maps.Marker({
position: pos3,
zIndex: 10,
map: map
});
var markerP4 = new google.maps.Marker({
position: pos4,
zIndex: 10,
map: map
});
createCurveMarker(markerP3, markerP4, map);
}
google.maps.event.addDomListener(window, 'load', init);
function createCurveMarker(marker1, marker2, map) {
var curveMarker;
function updateCurveMarker() {
var pos1 = marker1.getPosition(), // latlng
pos2 = marker2.getPosition(),
projection = map.getProjection(),
p1 = projection.fromLatLngToPoint(pos1), // xy
p2 = projection.fromLatLngToPoint(pos2);
// Calculate the arc.
// To simplify the math, these points
// are all relative to p1:
var e = new google.maps.Point(p2.x - p1.x, p2.y - p1.y), // endpoint (p2 relative to p1)
m = new google.maps.Point(e.x / 2, e.y / 2), // midpoint
o = new google.maps.Point(e.y, -e.x), // orthogonal
c = new google.maps.Point( // curve control point
m.x + curvature * o.x,
m.y + curvature * o.y);
var pathDef = 'M 0,0 ' +
'q ' + c.x + ',' + c.y + ' ' + e.x + ',' + e.y;
var zoom = map.getZoom(),
scale = 1 / (Math.pow(2, -zoom));
var symbol = {
path: pathDef,
scale: scale,
strokeWeight: 1,
fillColor: 'none'
};
if (!curveMarker) {
curveMarker = new google.maps.Marker({
position: pos1,
clickable: false,
icon: symbol,
zIndex: 0, // behind the other markers
map: map
});
} else {
curveMarker.setOptions({
position: pos1,
icon: symbol,
});
}
}
google.maps.event.addListener(map, 'projection_changed', updateCurveMarker);
google.maps.event.addListener(map, 'zoom_changed', updateCurveMarker);
}
html,
body,
#map-canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="map-canvas" ></div>

finding polygon center google map api 3

I want to find the center of a polygon in google map, I tried several solutions however none of them worked correctly for right triangle polygon here is example code:
var path = new Array(new google.maps.LatLng(1, 1), new google.maps.LatLng(1, 10), new google.maps.LatLng(10, 10), new google.maps.LatLng(1, 1));
var mapOptions = {
zoom: 4,
center: new google.maps.LatLng(40, 9),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
var polygon = new google.maps.Polygon({
path: path,
map: map
});
var bounds = new google.maps.LatLngBounds();
for (var i=0; i<polygon.getPath().length; i++) {
var point = new google.maps.LatLng(path[i].lat(), path[i].lng());
bounds.extend(point);
}
map.fitBounds(bounds);
const marker = new google.maps.Marker({
position: {
lat: bounds.getCenter().lat(),
lng: bounds.getCenter().lng()
},
map: this.map,
title: "Hello World!"
});
marker.setMap(map);
I used google.maps.LatLngBounds(); for finding cneter of the triangle and mark the center in the map however the result center is not actually true center of the triangle, jsfiddle example of this code.
I used another solution which is discussed here for finding the center of the polygon but that won't work either so is there any other solution for finding an accurate center of polygons regardless of polygon type?
points is array of polygon points,call getCenter to get coordinates of center.
var points = [[1,1],[1,10],[10,10]];
function getCenter(){
var sumX = 0, sumY = 0;
for(var i = 0; i < points.length; i++){
var point = points[i];
var x = point[0];
var y = point[1];
sumX += x;
sumY += y;
}
return {x:sumX / points.length,y:sumY / points.length};
}
var centerOfPoints = getCenter();

Intersection of two polygons in google map

I am trying to draw multiple polygons using google shapes API. I need to get the intersection of two polygons.
Here I can draw the background polygon(in black) by giving the array of path of each polygon.
Below is my code, here I am giving MVC Array as paths for polygon.
I just want the intersection area to be in separate color. Please check the screen shot link attached after the code.
var bgAreaCoordinates = [];
var bgbounds = map.getBounds(); // Boundary coordinates of the visible area of map
var NE = bgbounds.getNorthEast();
var SW = bgbounds.getSouthWest();
var bgPathCoordinates = [NE, new google.maps.LatLng(NE.lat(),SW.lng()),
SW, new google.maps.LatLng(SW.lat(),NE.lng())];
// Array of boundary coordinates of the visible part of the map
bgAreaCoordinates.push(bgPathCoordinates);
for (var key in flightPlanCoordinates) {
for (var k in flightPlanCoordinates[key]) {
bgAreaCoordinates.push(flightPlanCoordinates[key][k]);// Getting array of coordinates of each polygon
}
}
if (bgPath['bg']) {
bgPath['bg'].setMap(null); // remove the previous bg
}
console.info(bgAreaCoordinates);
bgPath['bg'] = new google.maps.Polygon({
// paths: [bgPathCoordinates, bgAreaCoordinates],
paths:bgAreaCoordinates,
geodesic: true,
strokeColor: '',
strokeOpacity: 0,
strokeWeight: 0,
fillColor: '#687472',
fillOpacity: 0.7
});
bgPath['bg'].setMap(map); // Draw the bg polygon : Google shapes Api
http://i.stack.imgur.com/VjTZe.png
Thanks in advance!
Here is an example that does what I think you want to do (make a hole in a polygon that covers the earth and cover that hole with a polygon with a different color). The example polygon happens to be a circle.
code snippet
// This example creates circles on the map, representing
// populations in the United States.
// First, create an object containing LatLng and population for each city.
var citymap = {};
citymap['chicago'] = {
center: new google.maps.LatLng(41.878113, -87.629798),
population: 2842518
};
citymap['newyork'] = {
center: new google.maps.LatLng(40.714352, -74.005973),
population: 8143197
};
citymap['losangeles'] = {
center: new google.maps.LatLng(34.052234, -118.243684),
population: 3844829
};
var cityCircle;
var bounds = new google.maps.LatLngBounds();
function drawCircle(point, radius, dir) {
var d2r = Math.PI / 180; // degrees to radians
var r2d = 180 / Math.PI; // radians to degrees
var earthsradius = 3963; // 3963 is the radius of the earth in miles
var points = 32;
// find the raidus in lat/lon
var rlat = (radius / earthsradius) * r2d;
var rlng = rlat / Math.cos(point.lat() * d2r);
var extp = new Array();
if (dir == 1) {
var start = 0;
var end = points + 1
} // one extra here makes sure we connect the ends
else {
var start = points + 1;
var end = 0
}
for (var i = start;
(dir == 1 ? i < end : i > end); i = i + dir) {
var theta = Math.PI * (i / (points / 2));
ey = point.lng() + (rlng * Math.cos(theta)); // center a + radius x * cos(theta)
ex = point.lat() + (rlat * Math.sin(theta)); // center b + radius y * sin(theta)
extp.push(new google.maps.LatLng(ex, ey));
bounds.extend(extp[extp.length - 1]);
}
return extp;
}
function initialize() {
// Create the map.
var mapOptions = {
zoom: 4,
center: new google.maps.LatLng(37.09024, -95.712891),
mapTypeId: google.maps.MapTypeId.TERRAIN
};
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
var outerbounds = [
new google.maps.LatLng(85, 180),
new google.maps.LatLng(85, 90),
new google.maps.LatLng(85, 0),
new google.maps.LatLng(85, -90),
new google.maps.LatLng(85, -180),
new google.maps.LatLng(0, -180),
new google.maps.LatLng(-85, -180),
new google.maps.LatLng(-85, -90),
new google.maps.LatLng(-85, 0),
new google.maps.LatLng(-85, 90),
new google.maps.LatLng(-85, 180),
new google.maps.LatLng(0, 180),
new google.maps.LatLng(85, 180)
];
var populationOptions = {
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35,
map: map,
paths: [outerbounds, drawCircle(citymap['newyork'].center, 10, -1)]
};
// Add the circle for this city to the map.
cityCircle = new google.maps.Polygon(populationOptions);
map.fitBounds(bounds);
var coverHole = new google.maps.Polygon({
strokeColor: '#FFFF00',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#0000FF',
fillOpacity: 0.35,
map: map,
paths: [drawCircle(citymap['newyork'].center, 10, -1)]
});
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map-canvas"></div>

Google Maps get the center of coordinates (place label at center of polygon)

I use Google maps, I mark areas on the maps like that:
var areaCoords2 = [
new google.maps.LatLng(32.819649, 35.073102),
new google.maps.LatLng(32.819604, 35.073026),
new google.maps.LatLng(32.817169, 35.071321),
new google.maps.LatLng(32.817097, 35.071353),
new google.maps.LatLng(32.816042, 35.073391),
new google.maps.LatLng(32.818513, 35.075119),
new google.maps.LatLng(32.818612, 35.075054)
];
I want to achieve: place the label and the marker in the middle(approximately) of the marked red area.
instead of place it with static Latitude and Longitude(I have a lot of areas)
There is a way of doing so programmatically?
The following code constructs a google.maps.Polygon and places a MapLabel at the center of its bounds.
// Construct the polygon.
var mypolygon2 = new google.maps.Polygon({
paths: polyCoords,
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 3,
fillColor: '#FF0000',
fillOpacity: 0.35
});
mypolygon2.setMap(map);
//Define position of label
var bounds = new google.maps.LatLngBounds();
for (var i=0; i< polyCoords.length; i++) {
bounds.extend(polyCoords[i]);
}
var myLatlng = bounds.getCenter();
var mapLabel2 = new MapLabel({
text: '2',
position: myLatlng,
map: map,
fontSize: 20,
align: 'left'
});
mapLabel2.set('position', myLatlng);
var obj = {};
obj.poly = mypolygon2;
obj.label = mapLabel2;
working fiddle
code snippet:
var map;
var gpolygons = [];
var infoWindow;
function initialize() {
var mapOptions = {
zoom: 17,
center: new google.maps.LatLng(50.71392, -1.983551),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
// Define the LatLng coordinates for the polygon.
var triangleCoords = [
new google.maps.LatLng(50.71433, -1.98392),
new google.maps.LatLng(50.71393, -1.98239),
new google.maps.LatLng(50.71388, -1.98226),
new google.maps.LatLng(50.71377, -1.98246),
new google.maps.LatLng(50.71332, -1.98296),
new google.maps.LatLng(50.71334, -1.98324),
new google.maps.LatLng(50.71374, -1.9845),
new google.maps.LatLng(50.71436, -1.98389)
];
// Construct the polygon.
var mypolygon = new google.maps.Polygon({
paths: triangleCoords,
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 3,
fillColor: '#FF0000',
fillOpacity: 0.35
});
mypolygon.setMap(map);
//Define position of label
var myLatlng = new google.maps.LatLng(50.71392, -1.983551);
var mapLabel = new MapLabel({
text: '1',
position: myLatlng,
map: map,
fontSize: 20,
align: 'left'
});
mapLabel.set('position', myLatlng);
var obj = {};
obj.poly = mypolygon;
obj.label = mapLabel;
gpolygons.push(obj);
var polyCoords = [
new google.maps.LatLng(50.713689004418, -1.9845771789550781),
new google.maps.LatLng(50.71316590540595, -1.9829249382019043),
new google.maps.LatLng(50.71296209901576, -1.983107328414917),
new google.maps.LatLng(50.71296889257639, -1.9837510585784912),
new google.maps.LatLng(50.713186285996215, -1.9845235347747803),
new google.maps.LatLng(50.71293492476347, -1.9847595691680908),
new google.maps.LatLng(50.71311155712187, -1.9853174686431885),
new google.maps.LatLng(50.71335612390394, -1.9853603839874268),
new google.maps.LatLng(50.713396884910225, -1.9850599765777588),
new google.maps.LatLng(50.71348520030224, -1.9848453998565674),
new google.maps.LatLng(50.71357351552787, -1.9846951961517334)
]
// Construct the polygon.
var mypolygon2 = new google.maps.Polygon({
paths: polyCoords,
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 3,
fillColor: '#FF0000',
fillOpacity: 0.35
});
mypolygon2.setMap(map);
//Define position of label
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < polyCoords.length; i++) {
bounds.extend(polyCoords[i]);
}
var myLatlng = bounds.getCenter();
var mapLabel2 = new MapLabel({
text: '2',
position: myLatlng,
map: map,
fontSize: 20,
align: 'left'
});
mapLabel2.set('position', myLatlng);
var obj = {};
obj.poly = mypolygon2;
obj.label = mapLabel2;
gpolygons.push(obj);
// Add a listener for the click event. You can expand this to change the color of the polygon
google.maps.event.addListener(mypolygon, 'click', showArrays);
google.maps.event.addListener(mypolygon2, 'click', showArrays);
infoWindow = new google.maps.InfoWindow();
}
/** #this {google.maps.Polygon} */
function showArrays(event) {
//Change the color here
// toggle it
if (this.get("fillColor") != '#0000ff') {
this.setOptions({
fillColor: '#0000ff'
});
} else {
this.setOptions({
fillColor: '#ff0000'
});
}
// Since this polygon has only one path, we can call getPath()
// to return the MVCArray of LatLngs.
var vertices = this.getPath();
var contentString = '<b>My polygon</b><br>' +
'Clicked location: <br>' + event.latLng.lat() + ',' + event.latLng.lng() +
'<br>';
// Iterate over the vertices.
for (var i = 0; i < vertices.getLength(); i++) {
var xy = vertices.getAt(i);
contentString += '<br>' + 'Coordinate ' + i + ':<br>' + xy.lat() + ',' + xy.lng();
}
// Replace the info window's content and position.
infoWindow.setContent(contentString);
infoWindow.setPosition(event.latLng);
infoWindow.open(map);
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map-canvas {
height: 100%;
margin: 0px;
padding: 0px;
}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<script src="https://cdn.rawgit.com/googlemaps/js-map-label/gh-pages/src/maplabel.js"></script>
<title>Polygon Arrays</title>
<div id="map-canvas">
</div>
Here is a method that does what you ask for Android/Java. You can try to adjust it for use in the web:
public Location GetCentrePointFromListOfLocations(List<Location> coordList)
{
int total = coordList.size();
double X = 0;
double Y = 0;
double Z = 0;
for(Location location : coordList)
{
double lat = location.getLatitude() * Math.PI / 180;
double lon = location.getLongitude() * Math.PI / 180;
double x = Math.cos(lat) * Math.cos(lon);
double y = Math.cos(lat) * Math.sin(lon);
double z = Math.sin(lat);
X += x;
Y += y;
Z += z;
}
X = X / total;
Y = Y / total;
Z = Z / total;
double Lon = Math.atan2(Y, X);
double Hyp = Math.sqrt(X * X + Y * Y);
double Lat = Math.atan2(Z, Hyp);
Location tempLocation = new Location("");
tempLocation.setLatitude(Lat * 180 / Math.PI);
tempLocation.setLongitude(Lon * 180 / Math.PI);
return tempLocation;
}
Did you add
zoom: 10,
center: myLatlng,
for you Marker Object
(or)
// map: an instance of GMap3
// latlng: an array of instances of GLatLng
var latlngbounds = new google.maps.LatLngBounds();
latlng.each(function(n){
latlngbounds.extend(n);
});
map.setCenter(latlngbounds.getCenter());
map.fitBounds(latlngbounds);
This one works for me with the dynamic polygon values.
<script type="text/javascript" src="https://cdn.rawgit.com/googlemaps/js-map-label/gh-pages/src/maplabel.js"></script>
<script>
// This example creates a simple polygon representing the Bermuda Triangle.
var gpolygons = [];
function initStaticMap() {
var bounds = new google.maps.LatLngBounds();
var latlng = new google.maps.LatLng(-22.5747697,-43.857650); //-22.820554842103107--43.184738187119365
var map = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: 10,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
});
// Define the LatLng coordinates for the polygon's path.
<?php if($store_delivery_zone){ foreach($store_delivery_zone as $point){ ?>
var coord<?php echo $point['delivery_zone_id']; ?> = <?php echo $point['polygon_points']; ?>;
// Construct the polygon.
var poly<?php echo $point['delivery_zone_id']; ?> = new google.maps.Polygon({
paths: coord<?php echo $point['delivery_zone_id']; ?>,
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35
});
poly<?php echo $point['delivery_zone_id']; ?>.setMap(map);
//var center = poly<?php echo $point['delivery_zone_id']; ?>.getBounds().getCenter();
//map.fitBounds(poly<?php echo $point['delivery_zone_id']; ?>.getBounds());
//Define position of label
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < coord<?php echo $point['delivery_zone_id']; ?>.length; i++) {
bounds.extend(coord<?php echo $point['delivery_zone_id']; ?>[i]);
}
var myLatlng<?php echo $point['delivery_zone_id']; ?> = bounds.getCenter();
var mapLabel<?php echo $point['delivery_zone_id']; ?> = new MapLabel({
text: '<?php echo $point['delivery_cost']; ?>',
position: myLatlng<?php echo $point['delivery_zone_id']; ?>,
map: map,
fontSize: 20,
align: 'left'
});
mapLabel<?php echo $point['delivery_zone_id']; ?>.set('position', myLatlng<?php echo $point['delivery_zone_id']; ?>);
var obj = {};
obj.poly = poly<?php echo $point['delivery_zone_id']; ?>;
obj.label = mapLabel<?php echo $point['delivery_zone_id']; ?>;
gpolygons.push(obj);
<?php } } ?>
google.maps.event.addListener(map, "idle", function()
{
google.maps.event.trigger(map, 'resize');
});
}
</script>
For Android/Java there is no need to start inventing an algorithm yourself, JTS is the package for such functionality.
// use jts to get suitable coordinate for label inside polygon
// convert google maps latlong to jts coordinates
List<Coordinate> jtsCoordinateList = new ArrayList<>();
for (LatLng gMapLatLng : polygon.getPoints())
jtsCoordinateList.add(new Coordinate(gMapLatLng.latitude, gMapLatLng.longitude));
Coordinate[] jtsCoordinateArray = jtsCoordinateList.toArray(new Coordinate[0]);
// create jts polygon
Geometry jtsGeometry = new GeometryFactory().createPolygon(jtsCoordinateArray);
// initiate InteriorPointArea
InteriorPointArea interiorPointArea = new InteriorPointArea(jtsGeometry);
// use InteriorPointArea to get the coordinate
Coordinate jtsInteriorPoint = interiorPointArea.getInteriorPoint();
// convert jts coordinate to google maps coordinate
LatLng polygonPoint = new LatLng(jtsInteriorPoint.getX(), jtsInteriorPoint.getY());
// use the calculated coordinate to place a marker
marker = createViewMarker(context, map, polygonPoint, legend);

Converting Google maps dynamic and resizing circle v2 to v3

http://web3o.blogspot.in/2010/05/google-maps-dynamically-movable-and.html
From the above link i got V2 google maps code which is working fine, but not able to import V3 beach markers so i convert the draw circle, circle resize and circle center marker function to V3 and i am not getting the circle in the maps where as i am getting all the marker, beach marker flags etc.
Following is the code, Kindly help me in fixing this, save the code as HTML file and execute in the browser.
I am having issue in the drawCircle function were the circle is not drawn on the Map.
<!--<script src="http://maps.google.com/maps?file=api&v=2&key=AIzaSyDAAkI8Q59oV68_F8r8hL66vlhCu9cWNQM&sensor=true" type="text/javascript"></script>-->
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&v=3&libraries=geometry"></script>
<script type="text/javascript">
/* Developed by: Abhinay Rathore [web3o.blogspot.com] */
//Global variables
var map;
var circle = [];
//circle[0] = {map_center: new GLatLng(38.903843, -94.680096),
// };
var Cobj = [];//{'mp_center':
var frndmap = [];
var bounds = new google.maps.LatLngBounds; //Circle Bounds
var map_center = new google.maps.LatLng(12.9735597, 77.6410402);
frndmap = [['Mahesh Pusala', 12.9735521, 77.6410431, 1], ['Bala Sundar', 12.9735567, 77.6410489, 2]];
var Circle=[];//null,null];//Circle object
var CirclePoints = []; //Circle drawing points
var CircleCenterMarker, CircleResizeMarker = [];//null,null];
var circle_moving = false; //To track Circle moving
var circle_resizing = false; //To track Circle resizing
var radius = []; //1 km
//var min_radius = 0.5; //0.5km
//var max_radius = 50; //5km
//Circle Marker/Node icons
/*var redpin = new google.maps.MarkerImage(); //Red Pushpin Icon
redpin.image = "http://maps.google.com/mapfiles/ms/icons/red-pushpin.png";
redpin.iconSize = new google.maps.Size(32, 32);
redpin.iconAnchor = new google.maps.Point(10, 32);*/
var redpin = new google.maps.MarkerImage('http://maps.google.com/mapfiles/ms/icons/red-pushpin.png',
// This marker is 20 pixels wide by 32 pixels tall.
new google.maps.Size(32, 32),
// The origin for this image is 0,0.
new google.maps.Point(0,0),
// The anchor for this image is the base of the flagpole at 0,32.
new google.maps.Point(10, 32));
/*var bluepin = new google.maps.MarkerImage(); //Blue Pushpin Icon
bluepin.image = "http://maps.google.com/mapfiles/ms/icons/blue-pushpin.png";
bluepin.iconSize = new google.maps.Size(32, 32);
bluepin.iconAnchor = new google.maps.Point(10, 32);*/
var bluepin = new google.maps.MarkerImage('http://maps.google.com/mapfiles/ms/icons/blue-pushpin.png',
// This marker is 20 pixels wide by 32 pixels tall.
new google.maps.Size(32, 32),
// The origin for this image is 0,0.
new google.maps.Point(0,0),
// The anchor for this image is the base of the flagpole at 0,32.
new google.maps.Point(10, 32));
function initialize() { //Initialize Google Map
//for(c in circle) {
//map = new GMap2(document.getElementById("map_canvas")); //New GMap object
var myOptions = {
zoom: 14,
center: map_center,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
/*addCircleResizeMarker(map_center[0], '0');
addCircleCenterMarker(map_center[0],'0');
drawCircle(map_center[0], radius, '0');
addCircleCenterMarker(map_center[1],'1');
addCircleResizeMarker(map_center[1], '1');
drawCircle(map_center[1], radius, '1');
*/
for(i=0; i<3; i++) {
Cobj[i] = {'map_center':new google.maps.LatLng(12.9735597+i, 77.6410402+i),
'Circle':null,
'CircleResizeMarker':null,
'radius':24+i
};
addCircleCenterMarker(i);
addCircleResizeMarker(i);
drawCircle(Cobj[i].map_center,Cobj[i].radius, i);
}
map.setCenter(map_center);
setMarkers(map, frndmap);
}
// Adds Circle Center marker
//radius
function addCircleCenterMarker(iii) {
point = Cobj[iii].map_center;
var markerOptions = { icon: bluepin, draggable: true };
CircleCenterMarker = new google.maps.Marker(point, markerOptions);
CircleCenterMarker.setMap(map); //Add marker on the map
//X= new google.maps.event();
google.maps.event.addListener(CircleCenterMarker, 'dragstart', function() { //Add drag start event
circle_moving = true;
});
google.maps.event.addListener(CircleCenterMarker, 'drag', function(point) { //Add drag event
drawCircle(point,Cobj[iii].radius, iii);
});
google.maps.event.addListener(CircleCenterMarker, 'dragend', function(point) { //Add drag end event
console.log(point.lng());
circle_moving = false;
drawCircle(point, Cobj[iii].radius, iii);
});
}
// Adds Circle Resize marker
// map_center
function addCircleResizeMarker(iii) {
point = Cobj[iii].map_center;
var resize_icon = new google.maps.MarkerImage(redpin);
resize_icon.maxHeight = 0;
var markerOptions = { icon: resize_icon, draggable: true };
Cobj[iii].CircleResizeMarker = new google.maps.Marker(point, markerOptions);
Cobj[iii].CircleResizeMarker.setMap(map); //Add marker on the map
google.maps.event.addListener(Cobj[iii].CircleResizeMarker, 'dragstart', function() { //Add drag start event
circle_resizing = true;
});
google.maps.event.addListener(Cobj[iii].CircleResizeMarker, 'drag', function(point) { //Add drag event
var new_point = new google.maps.LatLng(Cobj[iii].map_center.lat(), point.lng()); //to keep resize marker on horizontal line
var new_radius = new_point.distanceFrom(Cobj[iii].map_center) / 1000; //calculate new radius
//if (new_radius < min_radius) new_radius = min_radius;
//if (new_radius > max_radius) new_radius = max_radius;
drawCircle(Cobj[iii].map_center, new_radius, iii);
});
google.maps.event.addListener(Cobj[iii].CircleResizeMarker, 'dragend', function(point) { //Add drag end event
circle_resizing = false;
var new_point = new google.maps.LatLng(Cobj[iii].map_center.lat(), point.lng()); //to keep resize marker on horizontal line
var new_radius = new_point.distanceFrom(Cobj[iii].map_center) / 1000; //calculate new radius
//if (new_radius < min_radius) new_radius = min_radius;
//if (new_radius > max_radius) new_radius = max_radius;
console.log(new_radius);
drawCircle(Cobj[iii].map_center, new_radius, iii);
});
}
//Draw Circle with given radius and center
function drawCircle(center,new_radius, iii) {
//Circle = Circle[iii];
//Circle Drawing Algorithm from: http://koti.mbnet.fi/ojalesa/googlepages/circle.htm
//Number of nodes to form the circle
var nodes = new_radius * 40;
if(new_radius < 1) nodes = 40;
//calculating km/degree
xx = new google.maps.LatLng(center.lat() + 0.1, center.lng());
yy = new google.maps.LatLng(center.lat() , center.lng()+0.1);
var latConv = google.maps.geometry.spherical.computeDistanceBetween(center,xx)/100;//center.distanceFrom(new google.maps.LatLng(center.lat() + 0.1, center.lng())) / 100;
var lngConv = google.maps.geometry.spherical.computeDistanceBetween(center,yy)/100;//center.distanceFrom(new google.maps.LatLng(center.lat(), center.lng() + 0.1)) / 100;
CirclePoints = [];
var step = parseInt(360 / nodes) || 10;
var counter = 0;
for (var i = 0; i <= 360; i += step) {
var cLat = center.lat() + (new_radius / latConv * Math.cos(i * Math.PI / 180));
var cLng = center.lng() + (new_radius / lngConv * Math.sin(i * Math.PI / 180));
var point = new google.maps.LatLng(cLat, cLng);
CirclePoints.push(point);
counter++;
}
Cobj[iii].CircleResizeMarker.setPosition(CirclePoints[Math.floor(counter / 4)]); //place circle resize marker
CirclePoints.push(CirclePoints[0]); //close the circle polygon
if (Cobj[iii].Circle) {
//map.removeOverlay(Cobj[iii].Circle);
marker.setMap(null);
} //Remove existing Circle from Map
var fillColor = (circle_resizing || circle_moving) ? 'red' : 'blue'; //Set Circle Fill Color
console.log(CirclePoints);
Cobj[iii].Circle = new google.maps.Polygon(CirclePoints, '#FF0000', 2, 1, fillColor, 0.2); //New GPolygon object for Circle
//Cobj[iii].Circle.setMap(map); //Add Circle Overlay on the Map
//radius = new_radius; //Set global radius
//Cobj[iii].map_center = center; //Set global map_center
//if (!circle_resizing && !circle_moving)
//{
//Fit the circle if it is nor moving or resizing
// fitCircle(Cobj[iii].Circle);
//Circle drawing complete trigger function goes here
//}
}
//Fits the Map to Circle bounds
function fitCircle(Circle) {
bounds = Circle.getBounds();
map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
}
function setMarkers(map, locations) {
// Add markers to the map
// Marker sizes are expressed as a Size of X,Y
// where the origin of the image (0,0) is located
// in the top left of the image.
// Origins, anchor positions and coordinates of the marker
// increase in the X direction to the right and in
// the Y direction down.
var image = {
url: 'images/beachflag.png',
// This marker is 20 pixels wide by 32 pixels tall.
size: new google.maps.Size(20, 32),
// The origin for this image is 0,0.
origin: new google.maps.Point(0,0),
// The anchor for this image is the base of the flagpole at 0,32.
anchor: new google.maps.Point(0, 32)
};
var shadow = {
url: 'images/beachflag_shadow.png',
// The shadow image is larger in the horizontal dimension
// while the position and offset are the same as for the main image.
size: new google.maps.Size(37, 32),
origin: new google.maps.Point(0,0),
anchor: new google.maps.Point(0, 32)
};
// Shapes define the clickable region of the icon.
// The type defines an HTML <area> element 'poly' which
// traces out a polygon as a series of X,Y points. The final
// coordinate closes the poly by connecting to the first
// coordinate.
var shape = {
coord: [1, 1, 1, 20, 18, 20, 18 , 1],
type: 'poly'
};
for (var i = 0; i < locations.length; i++) {
var beach = locations[i];
var myLatLng = new google.maps.LatLng(beach[1], beach[2]);
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
shadow: shadow,
icon: image,
shape: shape,
title: beach[0],
zIndex: beach[3]
});
}
}
</script>
<body onload="initialize()">
<div id="map_canvas" style="width:100%; height:450px"></div>
</body>
Your drawCircle function has
Cobj[iii].Circle = new google.maps.Polygon(CirclePoints, '#FF0000', 2, 1, fillColor, 0.2); //New GPolygon object for Circle
Personally I'd rather use google.maps.Circle instead, much simpler
https://developers.google.com/maps/documentation/javascript/reference#Circle