Google Maps draw circle around radius search - javascript

I'm drawing a circle the size of the radius over which I'm performing a nearby search:
// Point where to search
var searchArea = new google.maps.LatLng(25.435833800555567, -80.44189453125);
// Draw a circle around the radius
var circle = new google.maps.Circle({
center: searchArea,
radius: parseFloat(document.getElementById("distance").value) * 1609.3, //convert miles to meters
strokeColor: "#0000FF",
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: "#0000FF",
fillOpacity: 0.4
});
circle.setMap(map);
// Perform search over radius
var request = {
location: searchArea,
radius: parseFloat(document.getElementById("distance").value) * 1609.3, //convert miles to meters
keyword: "coffee",
rankBy: google.maps.places.RankBy.PROMINENCE
};
service.nearbySearch(request, callback);
}
I then plot markers. This works fine but in some cases markers show outside the circle leading me to believe that it might not be the same size as the radius.
Here is a very good example of what I mean.
http://jsfiddle.net/hnPRh/2/
Notice how markers show outside the circle. Why is this happening?

The way I would do it is to calculate the distance from the center point. I've set your radius into a variable called RADIUS, make sure to place it where it is executed after the document has loaded.
I've also modified your for loop to include distance check. The distance function accepts 2 arguments which are both of type google.maps.LatLng
var EARTH_RADIUS = 6378137; // meters
var RADIUS = (parseFloat(document.getElementById("distance").value) * 1609.3);
function deg2rad(deg) {
return deg * (Math.PI / 180);
}
function distance(pos1, pos2) {
var p1Lat = pos1.lat(),
p1Lng = pos1.lng(),
p2Lat = pos2.lat(),
p2Lng = pos2.lng(),
dLat = deg2rad(p1Lat-p2Lat),
dLon = deg2rad(p1Lng-p2Lng),
a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(deg2rad(p1Lat)) * Math.cos(deg2rad(p2Lat));
return EARTH_RADIUS * (2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)));
}
for (var i = 0; i < results.length; i++) {
if (distance(results[i].geometry.location, searchArea) <= RADIUS) {
createMarker(results[i]);
}
}

Related

Distance calculation gives strange output javascript

I need to calculate the distance between two latitude and longitude points. I found this javascript code which I suppose I want.
Here comes the problem. I add the two positions lat and lng values in, and sometimes it just gives random output. What happens is two points literally next to other are sometimes like 8000 meters away, but two other much furthest points return only 1500 meters for example.
function degreesToRadians(degrees) {
return degrees * Math.PI / 180;
}
function getDistanceFromLatLonInKm(lat1,lon1,lat2,lon2) {
var R = 6371; // Radius of the earth in km
var dLat = deg2rad(lat2-lat1); // deg2rad below
var dLon = deg2rad(lon2-lon1);
var a =
Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) *
Math.sin(dLon/2) * Math.sin(dLon/2)
;
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R * c; // Distance in km
return d;
}
function deg2rad(deg) {
return deg * (Math.PI/180)
}
const distanceR = getDistanceFromLatLonInKm(userLat, userLng, solLat, solLng)
Lat: 68.00757101804007, lng: -49.306640625
to
lat: 73.26312194058698 lng: -23.535461425781254
is 1143 kilometres, but these two points are next to each other.
lat: 66.75724984139227, lng: -16.259765625000004
to
lat: 71.99597405683693 lng:-42.31933593750001
is 1161 metres and the points are much farther then the previus one.
Here I think it calculates fine, unlike the two previous lat and lng points.
I've tested the examples you provided and did a few on my own and I believe your implementation is working fine. I did however get different results using your examples and code.
The first example returns approx. 1102km, which seems close to the distance using a visualizer.
The second example returns 1161 kilometres which visualized again seems about right.
Please note: the images in the links were constructed using gpsvisualizer.com which uses a Vincenty formula to calculate distance, hence the slight variation in distance numbers.
function getDistanceFromLatLonInKm(lat1, lon1, lat2, lon2) {
var R = 6371; // Radius of the earth in km
var dLat = deg2rad(lat2 - lat1); // deg2rad below
var dLon = deg2rad(lon2 - lon1);
var a =
Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) *
Math.sin(dLon / 2) * Math.sin(dLon / 2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
var d = R * c; // Distance in km
return d;
}
function deg2rad(deg) {
return deg * (Math.PI / 180)
}
const e1 = {
lat1: 68.00757101804007,
lon1: -49.306640625,
lat2: 73.26312194058698,
lon2: -23.535461425781254
}
const e2 = {
lat1: 66.75724984139227,
lon1: -16.259765625000004,
lat2: 71.99597405683693,
lon2: -42.31933593750001
}
const dist1 = getDistanceFromLatLonInKm(e1.lat1, e1.lon1, e1.lat2, e1.lon2);
const dist2 = getDistanceFromLatLonInKm(e2.lat1, e2.lon1, e2.lat2, e2.lon2);
console.log(`Example 1 distance: ${dist1}km. Example 2 distance: ${dist2}km`);
I can not reproduce the issue you are having so I believe your error lies in your visualization of coordinates.

Google Maps Api draw my polygon (rectangle) as parallelogram

I can't manage with drawing rectangle between two cities. I've searched everywhere on the Internet and can't find out why my polygon is drawn on Google Maps as parallelogram even so on 2d plane (not earth plane) this rectangle is drawn properly.
What I noticed is that the curvature sides of parallelogram depends on where cities are placed on map. If two cities are placed vis-a-vis then my function draw rectangle successfully. But If they are placed diagonally then my function draw parallelogram. The result should be rotated rectangle with height as distance between two cities and width as kilometers that user chooses.
Here is my function that should draw rectangle between two cities. As args we need to give position of first city ($x1 is lat, $y1 is lng), position of second city and as third arg a radius in kilometers ($l1) from center point of rectangle.
function getPolygon($x1,$y1,$x2,$y2,$l1){
var $l1 = $l1*0.010526; //approx kilometers
var $distanceV = [($x2 - $x1), ($y2 - $y1)];
var $vlen = Math.sqrt(Math.pow($distanceV[0], 2) +
Math.pow($distanceV[1],2));
if($vlen == 0)
return [[0,0],[0,0],[0,0],[0,0]];
var $l2 = $vlen;
var $normalized = [($distanceV[0] / $vlen), ($distanceV[1] / $vlen)];
var $rotated = [(-1 * $normalized[1]), ($normalized[0])];
var $p1 = [($x1 - $rotated[0] * $l1 / 2), ($y1 - $rotated[1] * $l1 / 2)];
var $p2 = [($p1[0] + $rotated[0] * $l1), ($p1[1] + $rotated[1] * $l1)];
var $p3 = [($p1[0] + $normalized[0] * $l2), ($p1[1] + $normalized[1] * $l2)];
var $p4 = [($p3[0] + $rotated[0] * $l1), ($p3[1] + $rotated[1] * $l1)];
var $points = [
{lat: $p1[0], lng: $p1[1]},
{lat: $p3[0], lng: $p3[1]},
{lat: $p4[0], lng: $p4[1]},
{lat: $p2[0], lng: $p2[1]},
{lat: $p1[0], lng: $p1[1]}
];
return $points;
}
Then I draw it on Google Maps like this:
new google.maps.Polygon({
paths: getPolygon(first_city_lat, first_city_lng, second_city_lat, second_city_lng, 30),
strokeColor: '#FF0000',
strokeOpacity: 0.5,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.05
});
Here is an example should be rectangle between Birmingham and Oxford: JSFiddle
Additionally I'm sure that kilometers converter is not exact and it again depends how cities are placed.
The earth is curved. To get a polygon that appears rectangular on the curved sphere, you need to use calculations that take the projection of the map into account.
The Google Maps Javascript API v3 has a spherical geometry library that can be used to compute the desired points.
function getPolygon($x1,$y1,$x2,$y2,$l1){
var points = [];
var city1 = new google.maps.LatLng($x1, $y1);
var city2 = new google.maps.LatLng($x2, $y2);
var heading = google.maps.geometry.spherical.computeHeading(city1, city2);
points.push(google.maps.geometry.spherical.computeOffset(city1, $l1/2*1000, heading+90));
points.push(google.maps.geometry.spherical.computeOffset(city1, $l1/2*1000, heading-90));
points.push(google.maps.geometry.spherical.computeOffset(city2, $l1/2*1000, heading-90));
points.push(google.maps.geometry.spherical.computeOffset(city2, $l1/2*1000, heading+90));
points.push(points[0]);
return points;
}
proof of concept fiddle
code snippet:
var map;
google.maps.event.addDomListener(window, "load", function() {
var map = new google.maps.Map(document.getElementById("map_div"), {
center: new google.maps.LatLng(52.489471, -1.898575),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var trace = new google.maps.Polygon({
paths: getPolygon(52.489471, -1.898575, 51.752022, -1.257677, 30),
strokeColor: '#FF0000',
strokeOpacity: 0.5,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.05,
map: map
});
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < trace.getPath().getLength(); i++) {
bounds.extend(trace.getPath().getAt(i));
}
map.fitBounds(bounds);
function getPolygon($x1, $y1, $x2, $y2, $l1) {
var points = [];
var city1 = new google.maps.LatLng($x1, $y1);
var city2 = new google.maps.LatLng($x2, $y2);
var heading = google.maps.geometry.spherical.computeHeading(city1, city2);
points.push(google.maps.geometry.spherical.computeOffset(city1, $l1 / 2 * 1000, heading + 90));
points.push(google.maps.geometry.spherical.computeOffset(city1, $l1 / 2 * 1000, heading - 90));
points.push(google.maps.geometry.spherical.computeOffset(city2, $l1 / 2 * 1000, heading - 90));
points.push(google.maps.geometry.spherical.computeOffset(city2, $l1 / 2 * 1000, heading + 90));
points.push(points[0]);
return points;
}
});
html,
body {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px;
}
#map_div {
height: 95%;
}
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?libraries=geometry"></script>
<div id="map_div"></div>

Combine circles as polygon without intersecting common areas

I am creating a coverage map for my company's vendors, and then need to check how many of our customers live outside the overall coverage. A vendor's coverage area is always a circle.
I used this solution to combine the coverage areas of our vendors into a single polygon so that I can use the containsLocation function to compare out customer's locations. The problem is that the containsLocation function identifies some overlapping coverage areas as being outside coverage. Here is an example, where the pin should remain invisible because it is within the coverage of 2 vendors.
Overlapping Vendor Coverage Example
function updateMap(){
var radius = $('#radius').val();
$.ajax({
url: "",
dataType: "json",
type: "POST",
data: $('#dataForm').serialize()
}).done(function(result){
for(var i=0; i<result.length; i++){
center = {lat: parseFloat(result[i].Latitude), lng: parseFloat(result[i].Longitude)};
shapeArray.push(drawCircle(center, (radius), 1));
}
coverage = new google.maps.Polygon({
paths: shapeArray,
strokeColor: "#ff0000",
strokeOpacity: 0.8,
strokeWeight: 1,
fillColor: "#ff0000",
fillOpacity: 0.35,
map: map
});
});
}
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
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));
}
return extp;
}
function showUncovered(el){
if(!el.checked){
for(var i=0; i<markerArray.length; i++){
markerArray[i].setVisible(false);
}
return;
}
for(var i=0;i<markerArray.length;i++){
var pos = markerArray[i].position;
var isAffected = false;
if(!google.maps.geometry.poly.containsLocation(pos,coverage)){
markerArray[i].setVisible(true);
}
}
}
Google accepted this as a bug.
https://code.google.com/p/gmaps-api-issues/issues/detail?id=10609
Since you have all the circles you can iterate shapeArray and run .containsLocation(... in each circle, the first that contains the location ends the loop (if not, the marker is outside the polygon).
Actually, this is the solution proposed in the filed bug report (and looks like they won't fix it).

Polygon Draw around center points

I have tried lots but could not figure out the problem. I want to draw a polygon around specific lat,lng. The polygon will consists of 13 coordinates in specific radius.
Person inter the address and radius in text box.
Geo code get lat,lng of that address
Center the map to there.
Draw the polygon around that center point with radius
The polygon should consists of 13 coordinates
Code
function showAddress(address, miles) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
address : address
}, function(results, status) {
if(status == google.maps.GeocoderStatus.OK) {
//searchLocationsNear(results[0].geometry.location);
var cordinate = results[0].geometry.location;
//alert(cordinate);
var mapOptions = {
center : cordinate,
zoom : 8,
mapTypeId : google.maps.MapTypeId.ROADMAP,
overviewMapControl : true,
overviewMapControlOptions : {
opened : true,
position : google.maps.ControlPosition.BOTTOM_LEFT
}
};
//
//var address = document.getElementById("address").value;
var radius = 1;
var latitude = 23.1793013;
var longitude = 75.78490970000007;
//Degrees to radians
var d2r = Math.PI / 180;
// Radians to degrees
var r2d = 180 / Math.PI;
// Earth radius is 3,963 miles
var cLat = (radius / 3963) * r2d;
var cLng = cLat / Math.cos(latitude * d2r);
//Store points in array
var points = [];
alert("declare array");
var bounds = new google.maps.LatLngBounds();
// Calculate the points
// Work around 360 points on circle
for(var i = 0; i < 13; i++) {
var theta = Math.PI * (i / 180);
// Calculate next X point
circleY = longitude + (cLng * Math.cos(theta));
//console.log("CircleY:"+circleY);
// Calculate next Y point
circleX = latitude + (cLat * Math.sin(theta));
//console.log("circleX:"+circleX);
// Add point to array
var aPoint = new google.maps.LatLng(circleX, circleY);
points.push(aPoint);
bounds.extend(aPoint);
}
points.push(points[0]);
//console.log(points);
//to complete circle
var colors = ["#CD0000", "#2E6444", "#003F87"];
var Polyline_Path = new google.maps.Polyline({
path : points,
strokeColor : colors[0],
// color of the outline of the polygon
strokeOpacity : 1,
// between 0.0 and 1.0
strokeWeight : 1,
// The stroke width in pixels
fillColor : colors[1],
fillOpacity : 0
});
var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
Polyline_Path.setMap(map);
} else {
alert(address + ' not found');
}
});
}
Replace i<13;i++ by
i<360;i+=360/13
this will work
thank
edit: the last point isn't needed since gmap will close it automagically
I believe that cLng should be changed to:
var cLng = cLat * Math.cos(latitude * d2r);
(to get a perfect circle, that is)

bing maps: how to set zoom level so pinpoint is visible to users current location

I am using bing maps ajax v7 and for simplicity's sake let's say I have 10 PinPoints placed around the world. I'm trying to have the map zoom to the lowest level so that the closest PinPoint is still visible to the current location of the user. If someone could point me in the right direction I would greatly appreciate it.
$(document).ready(function () {
var windowHeight = $(window).height();
var windowWidth = $(window).width();
map = new Microsoft.Maps.Map(document.getElementById("mapDiv"), {
credentials: "myCredentials",
backgroundColor: "#A4C4ED",
zoom: 3,
height: windowHeight,
width: windowWidth
});
Microsoft.Maps.Events.addHandler(map, 'viewchange', hideInfoBox);
Microsoft.Maps.Events.addHandler(map, 'click', hideInfoBox);
//get users location and set view bound
var geoLocationProvider = new Microsoft.Maps.GeoLocationProvider(map);
var viewRectangle = Microsoft.Maps.LocationRect(geoLocationProvider.getCurrentPosition());
map.setView({ bounds: viewRectangle });
dataLayer = new Microsoft.Maps.EntityCollection();
map.entities.push(dataLayer);
var infoboxLayer = new Microsoft.Maps.EntityCollection();
map.entities.push(infoboxLayer);
//create initial infobox
infobox = new Microsoft.Maps.Infobox(new Microsoft.Maps.Location(0, 0), {
visible: false,
offset: new Microsoft.Maps.Point(0, 20)
});
infoboxLayer.push(infobox);
Microsoft.Maps.loadModule('Microsoft.Maps.Search', { callback: searchModuleLoaded });
});
I assume that you is one pin point and you have another 10 pin points located somewere on the map.
First you need to find the pinpoint that is closest to you.
You can use this function that expect two location objects that contains latitude and longitude.
oLocation1 = {latitude:0,longitude:0};
oLocation2 = {latitude:19,longitude:23};
function calcDistHaversine (oLocation1, oLocation2) {
var dLat = (oLocation2.latitude * Math.PI / 180 - oLocation1.latitude * Math.PI / 180);//*Math.PI*180;
var dLon = (oLocation2.longitude * Math.PI / 180 - oLocation1.longitude * Math.PI / 180);//*Math.PI*180;
var lat1 = oLocation1.latitude * Math.PI / 180;//*Math.PI*180;
var lat2 = oLocation2.latitude * Math.PI / 180;//*Math.PI*180;
var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.sin(dLon / 2) * Math.sin(dLon / 2) * Math.cos(lat1) * Math.cos(lat2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
var distance = 6371 * c;
return distance;
};
As a result you will get the distance between those two location with respect yo earth curvature.
Now you have your location and closest pinpoint location.
Lets name them as your,their.
Next you need to create array that contains those two location converted to microsoft location objects.
var yourLocation= new Microsoft.Maps.Location(your.latitude, your.longitude);
var theirLocation= new Microsoft.Maps.Location(their.latitude, their.longitude);
var arr = [];
arr.push(yourLocation);
arr.push(theirLocation);
Now you use bing maps feature that gives you best zoom and pointing according to given locations.
var bestView = Microsoft.Maps.LocationRect.fromLocations(arrLocations);
Then you set the map view according to the best view that we found.
setTimeout((function () {
map.setView({ bounds: bestView });
}).bind(this), 1000);

Categories

Resources