Algolia search, displaying all results even when radius set - google-maps

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?

Related

Google maps get position of an marker

I am adding multiple markers, and what I want to do is on click, get that specific marker position.
However at the moment it does work however it displays lat and lng for the last marker created. How can this be solved so that when I click on the marker it will give me that specific position of that marker.
function algolia_search(position) {
clearOverlays();
var APPLICATION_ID = '75RQSC1OHE';
var SEARCH_ONLY_API_KEY = 'f2f1e9bba4d7390fc61523a04685cf12';
var INDEX_NAME = 'businesses';
var PARAMS = { hitsPerPage: 20 };
// Client + Helper initialization
var algolia = algoliasearch(APPLICATION_ID, SEARCH_ONLY_API_KEY);
var algoliaHelper = algoliasearchHelper(algolia, INDEX_NAME, PARAMS);
// Map initialization
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._geoloc.lat, lng: hit._geoloc.lng},
map: map,
label: hit._geoloc.slug,
animation: google.maps.Animation.DROP
});
markers.push(marker);
marker.addListener('click', function() {
var destinationLat = marker.getPosition().lat();
var destinationLng = marker.getPosition().lng();
console.log(lat);
console.log(lng);
console.log(destinationLat);
console.log(destinationLng);
you need a listerner on map for click in event.latLng you have coordinates
google.maps.event.addListener(map, 'click', function(event) {
alert ( 'Lat : ' + event.latLng.lat() + ' Lng : ' + event.latLng.lng())
});
do the fact you have already place the marker on maps you could use a closure
var addListenerOnPoint = function(actMark){
actMark.addListener('click', function() {
alert ( 'Lat : ' + actMark.position.lat() + ' Lng : ' +actMark.position.lng());
});
for (i = 0; i < content.hits.length; ++i) {
var hit = content.hits[i];
var marker = new google.maps.Marker({
position: {lat: hit._geoloc.lat, lng: hit._geoloc.lng},
map: map,
label: hit._geoloc.slug,
animation: google.maps.Animation.DROP
});
addListenerOnPoint(marker,
);
markers.push(marker);
}

Algolia and google filter results based on user position

Hi I am using Google maps alongside algolia where I have an index 'locations' with 'lat' and 'lng'.
I am getting user location and watching position, I am also displaying markers from database based on lng and lat however I want to add a bit to it:
So I have followed that link:
https://www.algolia.com/doc/guides/geo-search/geo-search-overview/
And came up with:
#extends('master') #section('title', 'Live Oldham')
#section('extrafiles')
<script type="text/javascript" src="https://maps.google.com/maps/api/js?v=3&key=AIzaSyAirYgs4Xnt9QabG9v56jsIcCNfNZazq50&language=en"></script>
<script type="text/javascript" src="{!! asset('js/homesearch.js') !!}"></script>
#endsection
#section('content')
<div id="map_canvas" style="height:600px;"></div>
#endsection
and js:
$(document).ready(function() {
var map;
function initializeMap(){
map = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: 19,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
}
function locError(error) {
// the current position could not be located
alert("The current position could not be found!");
}
function setCurrentPosition(position) {
currentPositionMarker = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(
position.coords.latitude,
position.coords.longitude
),
title: "Current Position"
});
map.panTo(new google.maps.LatLng(
position.coords.latitude,
position.coords.longitude
));
}
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
console.log(latitude);
console.log(longitude);
function displayAndWatch(position) {
// set current position
setCurrentPosition(position);
// watch position
watchCurrentPosition(position);
console.log(position);
}
function watchCurrentPosition(position) {
var positionTimer = navigator.geolocation.watchPosition(
function (position) {
setMarkerPosition(
currentPositionMarker,
position,
)
});
}
function setMarkerPosition(marker, position) {
marker.setPosition(
new google.maps.LatLng(
position.coords.latitude,
position.coords.longitude)
);
}
function initLocationProcedure() {
initializeMap();
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(displayAndWatch, locError);
}else{
alert("Your browser does not support the Geolocation API");
}
}
$(document).ready(function() {
initLocationProcedure();
});
var APPLICATION_ID = '75RQSC1OHE';
var SEARCH_ONLY_API_KEY = 'f2f1e9bba4d7390fc61523a04685cf12';
var INDEX_NAME = 'locations';
var PARAMS = { hitsPerPage: 100 };
// Client + Helper initialization
var algolia = algoliasearch(APPLICATION_ID, SEARCH_ONLY_API_KEY);
var algoliaHelper = algoliasearchHelper(algolia, INDEX_NAME, PARAMS);
// Map initialization
var markers = [];
//alert("heelo");
var fitMapToMarkersAutomatically = true;
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];
console.log(hit)
var marker = new google.maps.Marker({
position: {lat: hit.longitude, lng: hit.latitude},
map: map,
title: hit.slug
});
markers.push(marker);
}
// Automatically fit the map zoom and position to see the markers
if (fitMapToMarkersAutomatically) {
var mapBounds = new google.maps.LatLngBounds();
for (i = 0; i < markers.length; i++) {
mapBounds.extend(markers[i].getPosition());
}
map.fitBounds(mapBounds);
}
});
function renderHits(content) {
$('#container').html(JSON.stringify(content, null, 2));
}
algoliaHelper.setQueryParameter('aroundRadius', 5000).search(); // 5km Radius
});
However there are few problems with this that I don't know how to tackle:
When user is moving, it doesn't center the map on the marker.
At this moment marker jumps between location when user moves, I would like for the marker to dynamically move on the map when user moves.
I want to use algolia to dynamically set markers, so I want to show markers with 5km radius from user location, and dynamically add or remove markers that are outside it.
I can't help you much with those questions since it's mostly about how to use GMap JS lib and I'm not experienced with it. However, something else catched my eyes:
var marker = new google.maps.Marker({
position: {lat: hit.longitude, lng: hit.latitude},
map: map,
title: hit.slug
});
You should put your coordinates in the _geoloc field in order to be able to use the geo-search features. It looks like this:
_geoloc: {
lat: 40.639751,
lng: -73.778925
}

Dynamic Load of Heatmap Data based on Map Bounds, Performance Issue

I have implemented a simple page that uses a listener to determine when a google maps bounds have changed because of zoom or pan. I am dynamically loading json data for a weighted heatmap summarized by the area visible in the map. It is working all except for the fact that I am not properly clearing the previous data from the heatmap on each call to the listener. Performance begins to degrade after the 4th or 5th call to fetch new data. I tried setting heatmap to null. What else is needed to maintain performance?
var map, heatmap;
var heatMapData = [];
function initMap() {
var uluru = { lat: 32.673363, lng: -97.399290 };
map = new google.maps.Map(document.getElementById('map'), {
zoom: 14,
center: uluru
});
google.maps.event.addListener(map, "bounds_changed", function () {
heatmap = null;
var bounds = map.getBounds();
//TODO: implement async request
var Httpreq = new XMLHttpRequest(); // a new request
var boxRequest = 'HeatMapData?lmin=' + bounds.f.f + '&lmax=' + bounds.f.b + '&lnmin=' + bounds.b.b + '&lnmax=' + bounds.b.f;
Httpreq.open("GET", boxRequest, false);
Httpreq.setRequestHeader("Content-type", "application/json")
var heatMapJSON = Httpreq.responseText;
heatMapData = [];
var parsedJSON = JSON.parse(heatMapJSON);
for (var i = 0; i < parsedJSON.length; i++) {
heatMapData.push({ location: new google.maps.LatLng(parsedJSON[i].Lat, parsedJSON[i].Lon), weight: parsedJSON[i].weight })
};
console.info('map points: ' + parsedJSON.length.toString());
heatmap = new google.maps.visualization.HeatmapLayer({
data: heatMapData,
map : map
});
});
if (heatmap != null) {
heatmap.setMap(null);
};

Google Map Route Arrow Line

I currently have these codes to load GPX File into Google Maps
function loadGPXFileIntoGoogleMap(map, filename) {
$.ajax({url: filename,
dataType: 'xml',
success: function(data) {
var parser = new GPXParser(data, map);
parser.setTrackColour('#ff0000'); // Set the track line colour
parser.setTrackWidth(5); // Set the track line width
parser.setMinTrackPointDelta(0.001); // Set the minimum distance between track points
parser.centerAndZoom(data);
parser.addTrackpointsToMap(); // Add the trackpoints
parser.addWaypointsToMap(); // Add the waypoints
}
});
}
$(document).ready(function() {
var mapOptions = {
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map'), mapOptions);
loadGPXFileIntoGoogleMap(map, '" . base_url('gps/ajax/request/trace') . "');
});
Everything is good but I want to replace it with arrow lines instead of straight line. Is it possible? If yes, please help me to do it.
In order to add arrows to the polylines created by the GPXParser, you need to modify that library to give access to the polylines, see the two lines and the function added to that library below. Then get the polylines and add the arrows to them as below.
working example (based off the example in the gpxviewer documentation referenced above)
Changes to the code from the example in the documentation:
function loadGPXFileIntoGoogleMap(map, filename) {
$.ajax({url: filename,
dataType: "xml",
success: function(data) {
var parser = new GPXParser(data, map);
parser.setTrackColour("#ff0000"); // Set the track line colour
parser.setTrackWidth(5); // Set the track line width
parser.setMinTrackPointDelta(0.001); // Set the minimum distance between track points
parser.centerAndZoom(data);
parser.addTrackpointsToMap(); // Add the trackpoints
// ******************** added *******************************
var polylines = parser.getPolylines();
// documentation on pre-defined symbols and repeated symbols:
// https://developers.google.com/maps/documentation/javascript/symbols
// Define a symbol using a predefined path (an arrow)
// supplied by the Google Maps JavaScript API.
var lineSymbol = {
path: google.maps.SymbolPath.FORWARD_OPEN_ARROW,
strokeColor: '#00FF00',
strokeOpacity: 1.0
};
for (var i=0; i<polylines.length; i++) {
polylines[i].setOptions({
icons: [{
icon: {
path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW,
strokeColor:'#0000ff',
fillColor:'#0000ff',
fillOpacity:1,
scale: 3
},
repeat:'100px'
}]
});
}
// *****************************end added**********************
parser.addWaypointsToMap(); // Add the waypoints
}
});
}
Changes to the loadgpx.js library:
function GPXParser(xmlDoc, map) {
this.xmlDoc = xmlDoc;
this.map = map;
this.trackcolour = "#ff00ff"; // red
this.trackwidth = 5;
this.mintrackpointdelta = 0.0001
this.polylines = []; // **added**
}
// return a reference to the array of polylines **added function**
GPXParser.prototype.getPolylines = function() {
return this.polylines;
}
GPXParser.prototype.addTrackSegmentToMap = function(trackSegment, colour,
width) {
var trackpoints = trackSegment.getElementsByTagName("trkpt");
if(trackpoints.length == 0) {
return;
}
var pointarray = [];
// process first point
var lastlon = parseFloat(trackpoints[0].getAttribute("lon"));
var lastlat = parseFloat(trackpoints[0].getAttribute("lat"));
var latlng = new google.maps.LatLng(lastlat,lastlon);
pointarray.push(latlng);
for(var i = 1; i < trackpoints.length; i++) {
var lon = parseFloat(trackpoints[i].getAttribute("lon"));
var lat = parseFloat(trackpoints[i].getAttribute("lat"));
// Verify that this is far enough away from the last point to be used.
var latdiff = lat - lastlat;
var londiff = lon - lastlon;
if(Math.sqrt(latdiff*latdiff + londiff*londiff)
> this.mintrackpointdelta) {
lastlon = lon;
lastlat = lat;
latlng = new google.maps.LatLng(lat,lon);
pointarray.push(latlng);
}
}
var polyline = new google.maps.Polyline({
path: pointarray,
strokeColor: colour,
strokeWeight: width,
map: this.map
});
this.polylines.push(polyline); // **added
}

Removing a Marker from an array in Google maps v3.0 problem

I've got this problem when removing a Marker from an array. I click on the map and place markers where i have clicked, the markers are then saved in an array. When removing them it only works in the order i have placed them but backwards, that means i place 1 2 3 but have to remove them like 3 2 1.
If i try to remove the markers in random order, the first one is removed, but then the others just stop working, the listener still works, but it seems like the forloop doesnt find the other markers in the array.
Any ideas? I'm completely lost.
Here is the code:
var map;
var tempLatLng;
var zoomLevel;
var markers = [];
var zoomLevels = [];
var count = -1;
var nullLatlng = new google.maps.LatLng(84.52,45.16);
var nullMarker = new google.maps.Marker({
position: nullLatLng,
});
function initialize() {
var myLatlng = new google.maps.LatLng(55.605629745598904,13.000441789627075);
var myOptions = {
zoom: 17,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
scrollwheel:false
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
//Puts a listener on the map, when clicking on the map, it places a marker.
google.maps.event.addListener(map, 'click', function(event) {
zoomLevel = map.getZoom();
document.getElementById("zoom").value = zoomLevel;
tempLatLng = event.latLng;
setTimeout("placeMarker(tempLatLng)", 800); //placeMarker is called with a duration so that //doubleclicking doesn't bother the placement.
});
}
//Function to place markers.
function placeMarker(location) {
if(zoomLevel == map.getZoom()){
if(true){
var marker1 = new google.maps.Marker({
position: location,
map: map,
draggable:true
});
count = count + 1;
markers[count] = marker1;
document.getElementById("count").value = count;
google.maps.event.addListener(marker1,'rightclick', function(event){
document.getElementById("test2").value = "funkar";
for(var i = 0 ;i < markers.length ;i++){
if(markers[i].getTitle() == marker1.getTitle()){
marker1.setMap(null);
document.getElementById("markerpos").value = markers[i].getTitle();
document.getElementById("test1").value = markers[i].getTitle();
count = count - 1;
document.getElementById("count").value = count;
markers[i] = nullMarker;
}
}
});
marker1.setTitle(location.toString());
}
map.setCenter(location);
}
}
Here is the JSFiddle Demo:
Basically, you were using var count to keep track of the number of markers. You can do markers.length for that. Instead of using markers[count] you can use native array's push method to add element into the array. To remove use splice(i, 1); where i is the element's position and remove 1 element from that position. Also, to check if two markers are equal or the "same" instead using getTitle() use === which does:
is exactly equal to (value and type)
The problem is if you create two or more markers on the same position it would remove both markers but in reality you only remove one of the two "clones" and thus leaving a marker un-removable. This is caused by using getTitle which returns lat lng and if you have two markers w/ same lat lng you have an issue. Also, i changed, within your onclick function, marker1 to this which are referring to the same object for readability.
//Function to place markers.
function placeMarker(location) {
if (zoomLevel == map.getZoom()) {
if (true) {
var marker1 = new google.maps.Marker({
position: location,
map: map,
draggable: true
});
count = count + 1;
markers.push(marker1);
document.getElementById("count").value = markers.length;
google.maps.event.addListener(marker1, 'rightclick', function(event) {
document.getElementById("test2").value = "funkar";
for (var i = 0; i < markers.length; i++) {
if (markers[i] === this) {
this.setMap(null);
document.getElementById("markerpos").value = markers[i].getTitle();
document.getElementById("test1").value = markers[i].getTitle();
markers.splice(i, 1);
document.getElementById("count").value = markers.length;
}
}
});
marker1.setTitle(location.toString());
}
map.setCenter(location);
}
}