Average Lng/Lat NaN Issues - google-maps

I'm an amateur programmer and working on a project I have in mind using the google maps API. Long story short, I'm trying to create a variable with the average longitude and latitude of n number of points. I'm to the point that I have an array of the lng/lat coordinates, but I'm struggling to convert them into a format that I can use as input for a google maps LatLng method.
I've referenced this SO question, Find the average (center) of lats/lngs, and numerous other websites for a month now, but I haven't been able to understand or implement a solution. I feel like I'm missing the simple stuff, but I've been banging my head against this for a month, and not getting anywhere. Any advice or help with this would be appreciated.
//GOOGLE MAPS API SCRIPTS
var streetarray = document.getElementsByName("street");
var cityarray = document.getElementsByName("city");
var geocoder;
var map;
var results;
var mapArray = new Array();
var avgLat;
var avgLng;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var mapOptions = {
zoom: 8,
//centered on Carrollton, Texas -- Change lat,long values to change initial map area
center:
new google.maps.LatLng(32.999173, -96.897413)
}
//change Id reference to the div/container that contains the google map
map = new google.maps.Map(document.getElementById('map'), mapOptions);
}
function codeAddress() {
//Loop through and concate street and city values to find long,lat values for all fields
for (var cName = 0; cName < namearray.length; cName++){
var address = streetarray[cName].value + cityarray[cName].value;
//start geocode copy & paste text from API reference
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var results = results[0].geometry.location;
map.setCenter(results);
var marker = new google.maps.Marker({
map: map,
position: results,
});
//Push lng/lat locations to the mapArray
mapArray.push(results);
//Loop through mapArray to add Lat/Lng values, and then divide by j (number of locations) to find the average
for (var i in mapArray) {
var avgLat = 0;
var avgLng = 0;
var j = 0;
var avgLat = (avgLat + mapArray[i][1]);
var avgLng = (avgLng + mapArray[i][2]);
console.log(mapArray, avgLat, avgLng);
j++;
}
avgLat = avgLat / j;
avgLng = avgLng / j;
var markerCircle = new google.maps.Circle({
center: results,
radius: 15000,
strokeColor:"#0000FF",
strokeOpacity:0.8,
strokeWeight:2,
fillColor:"#0000FF",
fillOpacity:0.4
})
markerCircle.setMap(map);
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}}

2 issues:
results[0].geometry.location is not an array, it's an object(a google.maps.LatLng). Use the methods lat() and lng() to retrieve latitude and longitude
var avgLat = 0;
var avgLng = 0;
var j = 0;.
You must move this to outside of the loop, otherwise the variables will be cleared on each loop.

Related

Algolia search, displaying all results even when radius set

So I want to search by lat and lng within 5km radius, despite limiting hits per page to 10, it is still displaying all markers on map and there are 96, why isn't this working properly?
var APPLICATION_ID = '**';
var SEARCH_ONLY_API_KEY = '**';
var INDEX_NAME = 'locations';
var PARAMS = { hitsPerPage: 10 };
// Client + Helper initialization
var algolia = algoliasearch(APPLICATION_ID, SEARCH_ONLY_API_KEY);
var algoliaHelper = algoliasearchHelper(algolia, INDEX_NAME, PARAMS);
algoliaHelper.setQueryParameter('aroundLatLng', '53.552472, -2.807663');
algoliaHelper.setQueryParameter('aroundRadius', 5000);
algoliaHelper.search();
// Map initialization
var markers = [];
//alert("heelo");
algoliaHelper.on('result', function(content) {
renderHits(content);
var i;
// Add the markers to the map
for (i = 0; i < content.hits.length; ++i) {
var hit = content.hits[i];
var marker = new google.maps.Marker({
position: {lat: hit.longitude, lng: hit.latitude},
map: map,
label: hit.slug,
animation: google.maps.Animation.DROP
});
markers.push(marker);
}
});
function renderHits(content) {
$('#container').html(JSON.stringify(content, null, 2));
}
});
How a very weird reason if I delete:
algoliaHelper.setQueryParameter('aroundLatLng', '53.552472, -2.807663');
algoliaHelper.setQueryParameter('aroundRadius', 5000);
algoliaHelper.search();
It still brings back all records, does anyone have a clue why is this happening?

How to get the lat and lng of dragged waypoint

I am making this app where I let the user draw a waypoints route with google maps directions service and currently I am working on the edit route page - that is where the user can drag the waypoints of the route to reorder them. I am having trouble getting the lat and lng of the currently dragged waypoint.
How can I access the lat/lng of the dragged waypoint object on drag end?
This is my code:
<script type="text/javascript">
var rendererOptions = {
draggable: true
};
var phpway = <?php echo json_encode($phpway); ?>;
var directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);;
var directionsService = new google.maps.DirectionsService();
var map;
var waypts = [];
for(var i = 0; i < phpway.length; i+=2){
waypts.push(new google.maps.LatLng(Number(phpway[i]), Number(phpway[i+1])));
}
var start = waypts[0];
var end = waypts[waypts.length-1];
var mywaypts = [];
var pointsArray = [];
for (var i = 1; i < waypts.length-1; i++) {
mywaypts.push({
location:waypts[i],
stopover:true});
}
var australia = new google.maps.LatLng(-25.274398, 133.775136);
function initialize() {
var mapOptions = {
zoom: 7,
center: australia
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('directionsPanel'));
google.maps.event.addListener(directionsDisplay, 'directions_changed', function() {
//computeTotalDistance(directionsDisplay.getDirections());
calcRoute();
});
calcRoute();
}
function calcRoute() {
console.log(start);
var request = {
origin: start,
destination: end,
waypoints: mywaypts,
optimizeWaypoints: true,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
In the 'directions_changed' event handler, process through the "new" directions returned from:
directionsDisplay.getDirections(). The start/end locations of each leg are the waypoints (note that the end of the first leg will be the same point as the start of the second).
google.maps.event.addListener(directionsDisplay, 'directions_changed', function () {
document.getElementById('waypoints').innerHTML = "";
var response = directionsDisplay.getDirections();
var route = response.routes[0];
var path = response.routes[0].overview_path;
var legs = response.routes[0].legs;
for (i=0;i<legs.length;i++) {
document.getElementById('waypoints').innerHTML += legs[i].start_location.toUrlValue(6) +":";
document.getElementById('waypoints').innerHTML += legs[i].end_location.toUrlValue(6)+"<br>";
}
});
fiddle
Inspect var dirs = directionsDisplay.getDirections();, maybe using console.log(dirs); to get a glance at the request format.
You will find the origin under dirs.request.origin, the destination under dirs.request.destination and the waypoints under dirs.request.waypoints.
To find the waypoint you have just ended dragging, keep the previous request (there should always be one, even before the first drag, since you first load the the route to be edited) and search for the differences in between this previous request and the current one via a simple iteration through the 'set of waypoints'. I suspect that there should be only one difference you find between the two (no matter if you introduce a new waypoint or you move an already existing one). That is your last dragged waypoint.

google api to search nearby address using their latitude,longitude from database

I need to retrieve a set of nearby addresses from google api using their latitude,longitude values.Latitude,longitude values are retrieved from a database.Is there a way to accomplish this?
Use Google Maps Javascript Api.
https://developers.google.com/maps/documentation/javascript/examples/geocoding-reverse
And Read a developer guide https://developers.google.com/maps/documentation/javascript/tutorial
Here is how it can be done with a combination of jquery and the google api. the $.getJSON call is invoking a service that gets a list of lat/lng objects in a pretty standard name and address kind of format and pushes everything into a marker array.
In this example the user enters an address in the "useradd" control, which becomes one blue marker, and some nearby things in the database are displayed as red markers.
I have found the map to be very sensitive to styling changes, especially modifying it's height and width, I am sure there is some way to deal with that, just have not found it yet.
<script type="text/javascript">
var geocoder;
var map;
var markersArray = [];
//---------------------------------------------------------------------------------------------------------------
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(0, 0); //add some real starting coords
var mapOptions = {
zoom: 12,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
$('#loadMsg').hide().ajaxStart(function () { $(this).show(); }).ajaxStop(function () { $(this).hide(); });
}
//---------------------------------------------------------------------------------------------------------------
function getStringfromJSON(invalue) {
if (!invalue) { return ''; } else { return invalue; }
}
function codeAddress() {
var address = document.getElementById("useradd").value;
if (address.length == 0) return;
if (markersArray) {
for (i in markersArray) {
markersArray[i].setMap(null);
}
markersArray.length = 0;
}
geocoder.geocode
(
{ 'address': address },
function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var blueIcon = new google.maps.MarkerImage("http://www.google.com/intl/en_us/mapfiles/ms/micons/blue-dot.png");
var marker = new google.maps.Marker({ map: map, position: results[0].geometry.location, icon: blueIcon, clickable: false });
marker.setTitle(address);
var lat = results[0].geometry.location.lat();
var lng = results[0].geometry.location.lng();
var dist = document.getElementById("selMiles").value;
var pageurl = '../Search/GetNearbys?lat=' + lat + '&lng=' + lng + '&dist=' + dist;
$.getJSON(pageurl,
function (data) {
for (var x = 0; x < data.length; x++) {
var facid = data[x].ID;
var facname = getStringfromJSON(data[x].Name);
var streetaddress = getStringfromJSON(data[x].StreetAddress);
var address2 = getStringfromJSON(data[x].Address2);
var city = getStringfromJSON(data[x].City);
var state = getStringfromJSON(data[x].State);
var zip = getStringfromJSON(data[x].ZipCode);
var xlat = data[x].Latitude;
var xlng = data[x].Longitude;
var xlatlng = new google.maps.LatLng(xlat, xlng);
var xmarker = new google.maps.Marker({ map: map, position: xlatlng, facilityid: facid });
xmarker.setTitle(facname + ' ' + streetaddress + ' ' + address2 + ' ' + city + ',' + state + ' ' + zip);
markersArray.push(xmarker);
google.maps.event.addListener(xmarker, 'click',
function () {
window.open('../Profile?id=' + this.facilityid, '_blank');
});
}
},
function (succeess) { }
);
}
else {
alert("Geocode was not successful for the following reason: " + status);
}
markersArray.push(marker); //put it here so it gets reset after each search
}
);
}
</script>

Google Maps Directions dragged polyline coordinates reset after extending the route

Hey guys, the function of this code is described below.
there are some predefined functions below i.e getMapOption and others
function initialize(){
var divCalcDis = $('divCalcDis');
var pdist = $('pdist');
var pTimeTaken = $('pTimeTaken');
var txtLatLon = $('divLatLon');
var lblDistance = $('lblDistance');
var mapOption = mapHandler.getMapOption(that.LonLatCoordinates[0], 15, "Default");
map = mapHandler.getMap('map_canvas', mapOption);
var renderOption = { draggable: true };
directionsDisplay = new google.maps.DirectionsRenderer(renderOption);
directionsDisplay.setMap(map);
google.maps.event.addListener(directionsDisplay, 'directions_changed', function () { for (i = 0; i < directionsDisplay.directions.routes.length; i++) {
//getting latlon
txtLatLon.innerHTML = "";
console.log(directionsDisplay.directions.routes[i].overview_path.length);
var latLng = directionsDisplay.directions.routes[i].overview_path[k];
var latLng = directionsDisplay.directions.routes[i].overview_path[directionsDisplay.directions.routes[i].overview_path.length - 1].toString();
latLng = latLng.split('(')[1];
latLng = latLng.split(')')[0];
latLng = latLng.split(' ');
latLng = latLng[0] + latLng[1];
txtLatLon.innerHTML += latLng;
}
});
startMap();
}
function startMap() {
var i=0;
google.maps.event.addListener(map, 'click', function (event) {
i++;
if(i === 1){
mapHandler.setMarker(event.latLng, map, "http://www.google.com/intl/en_us/mapfiles/ms/micons/green-dot.png", null, null, null, that.permanentMarkers, false);
that.origin = event.latLng; //comma seperated values of lat,lon
}
else if(i > 1){
mapHandler.setMarker(event.latLng, map, "http://www.google.com/intl/en_us/mapfiles/ms/micons/green-dot.png", null, null, null, that.permanentMarkers, false);
if (i === 2) {
that.dest = event.latLng; //comma seperated values of lat,lon
}
else if (i > 2) {
that.wayPTs.push({
location: that.dest,
stopover: true
});
that.dest = event.latLng;
}
that.calcRoute();
}});
};
function calcRoute() {
var divCalcDis = stringHandler._id('divCalcDis');
var pdist = stringHandler._id('pdist');
var pTimeTaken = stringHandler._id('pTimeTaken');
var txtLatLon = stringHandler._id('divLatLon');
txtLatLon.innerHTML = "";
if (!that.wayPTs.length > 1) {
this.wayPTs = null;
}
var request = this.directionsRequest(this.origin,this.dest,google.maps.DirectionsTravelMode.DRIVING,this.wayPTs,false,true,true,google.maps.DirectionsUnitSystem.METRIC);
that.directionsResponse.route(request, function (response, status) {
//console.log(response);
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
};
**
I am making a project using Google Maps API V3 Directions library in which i am creating a route when a user click some place on the map
Here is a screenshot**
Now when i drag the direction drawn line it works smoothly and giving me the latitude and longitude correctly.
Here is a screenshot
But the Problem is when i click on anyother place on the map(after dragging) the waypoint refreshes and i get the old without drag route with the next stop as you can see below
Here is a Screenshot
How to save the latLon of the waypoint so they are available after creation of new points Thx
You need to push the coordinates into the route array so they will always be available. So push when you drag and push when you click. May be this can be of assistance to you. Best of luck.

Google fusion tables data and changing image to markers

Here is my problem. I want to set different image to standard markers given by fusion tables. I extract data from the column that contains my points "(coord,coord)" BUT when I associate this coordinates to a marker, this one is not showed! I think that the solution is soooo easy but I can't get it :(. Please read in the section "HERE IS THE PROBLEM" in the middle of this code to have a clear idea. Thanks!!!!
function initialize() {
geocoder = new google.maps.Geocoder();
map = new google.maps.Map(document.getElementById('map_canvas'), {
center: new google.maps.LatLng(46.06454, 13.23561), //the center lat and long
zoom: 9, //zoom
mapTypeId: google.maps.MapTypeId.ROADMAP //the map style
});
//make gviz request
setData();
}
/* GVIZ - get data from Fusion Tables */
function setData() {
//create a viz query to send to Fusion Tables
var query = new google.visualization.Query('http://www.google.com/fusiontables/gvizdata?tq=' + encodeURIComponent("SELECT dove FROM 781907"));
//set the callback function that will be called when the query returns
query.send(getData);
}
function getData(response) {
numRows = response.getDataTable().getNumberOfRows();
for (i = 0; i < numRows; i++) {
var row = response.getDataTable().getValue(i,0);
codeAddress(row);
}
}
var geocoder;
function codeAddress(latlng) {
// HERE IS THE PROBLEM!!!!
// Test show correctly "(lat,lng)" BUT no marker showed on the map!
document.getElementById("test").innerHTML = latlng;
geocoder.geocode( { 'latLng': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var marker = new google.maps.Marker({
map: map,
position: latlng
//icon: new google.maps.MarkerImage("http://www.google.com/images/icons/product/fusion_tables-32.png")
});
}
});
}
UPDATE: Based on #Trott's answer, maybe something like this? But still not running. Any advice?
function getData(response) {
numRows = response.getDataTable().getNumberOfRows();
//create an array of row values
for (i = 0; i < numRows; i++) {
rowtext = response.getDataTable().getValue(i,0);
var strArr[] = rowtext.split(",");
document.getElementById("via").innerHTML = rowtext;
row = new google.maps.LatLng(strArr[0],strArr[1]);
codeAddress(row);
}
}
geocoder.geocode() requires a LatLng object. Your variable latlng is simply text. You'll need to find a way to convert it to a LatLng object. Most obvious way is probably to parse it with a regex or some other way and pass the lat and lng to new google.maps.LatLng(). There may be a more elegant solution, but that will work.
If it helps, here's some quick hacking I did to your code to confirm what I wrote above. I just hardcoded your first pair of coordinates. You'll still need to write something to parse the data.
function codeAddress(latlng) {
//Whoops, latlng is a string. We need it to be an object. Let's just hardcode one for demo purposes.
latlng=new google.maps.LatLng(46.0724339, 13.249490000000037);
geocoder.geocode( { 'latLng': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var marker = new google.maps.Marker({
map: map,
position: latlng,
icon: new google.maps.MarkerImage("http://www.google.com/images/icons/product/fusion_tables-32.png")
});
}
});
}
UPDATE: If you (#Massimo) want to do it the way you have it in your update, then you need to remove the parentheses and possibly white space. Try something more like this:
function getData(response) {
numRows = response.getDataTable().getNumberOfRows();
//create an array of row values
for (i = 0; i < numRows; i++) {
var rowtext = response.getDataTable().getValue(i,0);
var sanitizedText = rowtext.replace(/[\(\)\s]/g, "");
var strArr = sanitizedText.split(",");
document.getElementById("via").innerHTML = rowtext;
row = new google.maps.LatLng(strArr[0],strArr[1]);
codeAddress(row);
}
}