Get total marker count from Google API placesSearch - javascript

In the example fiddle, how can I get the total number of markers displayed on the map? I'm pushing each of the markers into an array like this:
markers.push(marker)
And attempting to get the total number of markers like this:
$('.marker-count span').html(markers.length);
Unfortunately, "markers.length" is returning 0 when it should be returning at least 3.
I have example code here: http://jsfiddle.net/287C7/
How can I display the total number of markers? Is it not possible to add each marker to my array?
I need to know the amount of markers shown so that I can alert the user if there are none.
Thanks,
In case you don't want to view the code on jsfiddle.net, here it is:
var map, places, tmpLatLng, markers = [];
var pos = new google.maps.LatLng(51.5033630,-0.1276250);
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(51.5033630,-0.1276250)
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
// create the map and reference the div#map-canvas container
var markerBounds = new google.maps.LatLngBounds();
var service = new google.maps.places.PlacesService(map);
// fetch the existing places (ajax)
// and put them on the map
var request = {
location: pos,
radius: 48000, // Max radius
name: "mc donalds"
};
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
$('#map-canvas').attr("data-markers",results.length);
$('.marker-count span').html(markers.length);
} else {
console.log("Places request failed: "+status);
}
} // end callback
function createMarker(place) {
var prequest = {
reference: place.reference
};
var tmpLatLng = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
markers.push(marker);
markerBounds.extend( tmpLatLng );
} // end createMarker
service.nearbySearch(request, callback);

the placesSearch call is asynchronous, when you run your code:
$('.marker-count span').html(markers.length);
the result hasn't come back from the server yet. You need to do that in the call back after you update the markers array.
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
$('#map-canvas').attr("data-markers",results.length);
$('.marker-count span').html(markers.length);
} else {
console.log("Places request failed: "+status);
}
} // end callback
working fiddle

Related

Variable overwritten by ajax response

Using Google Maps and the Geocoder, I'm trying to loop over an object of addresses, return LatLng addresses for them, and create markers using both the original details and the latlng address in the setMarker function below.
The problem is, the response[a] is being overwritten by the last address in the object, because the for loop is running ahead of the AJAX results being returned.
How can I save the data in the current response[a] being looped over, so that when setMarker() is later called, it contains the right information?
Thanks
var limit = 0;
for (a in response){
if(limit<5){ // limit API calls
var addr = [response[a].Addr1, response[a].City, response[a].Zip];
geo = new google.maps.Geocoder();
geo.geocode({
address: addr.join(", "),
componentRestrictions: {
// country: 'UK'
}
}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK && results) {
var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();
var latlng = new google.maps.LatLng(latitude, longitude);
if(latitude!="" && longitude!=""){
bounds.extend(latlng);
map.fitBounds(bounds);
_this.setMarker(map, limit, latlng, response[a]);
}
} // if geo results
});
}
limit++;
}
The problem you are facing is a classic one that can be solved using closure function.
Current code looks something like :
var a[20];
for(i=0;i<20;i++) {
some_async_method() {
//code that uses 'a[i]'
}
}
Using closure to preserve the scope of var a inside a async function :
var a[20];
for(i=0;i<20;i++) {
(function(_a){
some_async_method() {
//code that uses 'a[i]' as '_a'
}
})(a[i]);// self calling function that preserves the scope of a[i]
}
So your code will look like :
var limit = 0;
for (a in response){
if(limit<5){ // limit API calls
var addr = [response[a].Addr1, response[a].City, response[a].Zip];
geo = new google.maps.Geocoder();
(function(response_a){ // closure function to preserve scope of 'response[a]'
geo.geocode({
address: addr.join(", "),
componentRestrictions: {
// country: 'UK'
}
}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK && results) {
var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();
var latlng = new google.maps.LatLng(latitude, longitude);
if(latitude!="" && longitude!=""){
bounds.extend(latlng);
map.fitBounds(bounds);
_this.setMarker(map, limit, latlng, response_a);
}
} // if geo results
});
})(response[a]);
}
limit++;
}

pointing markers on Google map #change

I have included google map for the project that I'm working with. I have few checkboxes which are dynamic and when click on a checkbox according to that those locations will be displayed on google map. As follows: The thing is it is not refreshing and remove the previous markers when I check or uncheck those checkboxes again and again.
Vue Component:
<div v-for="vnos in vehicle_nos">
<input class="" type="checkbox" name="vehicle_num" :value="vnos.name" v-model="vehicle_nums" #change="getVehicleNumbers(vehicle_nums)">
<label for="vehicle_num">{{vnos.name}}</label><br>
</div>
functions I trigger:
getVehicleNumbers(vehicle_num){
this.allSelectedVehicles = vehicle_num;
axios.post('gps/get-gps-location/'+this.allSelectedVehicles)
.then(response => {
for (let i = 0; i < response.data.data.length; i++) {
this.all_data = JSON.parse(response.data.data[i]);
this.longtitudes = this.all_data.item.pos.x;
this.latitudes = this.all_data.item.pos.y;
let longlatitude = this.latitudes+','+this.longtitudes;
this.geocoder = new google.maps.Geocoder;
this.infowindow = new google.maps.InfoWindow;
//here I pass those coordinates to geocodeLatLng() function
this.geocodeLatLng(this.geocoder, this.map, this.infowindow, longlatitude);
}
}).catch(Erors => {
console.log('errors');
});
},
geocodeLatLng(geocoder, map, infowindow, longlatitude = null) {
var input = longlatitude;
var latlngStr = input.split(',', 2);
var latlng = {lat: parseFloat(latlngStr[0]), lng: parseFloat(latlngStr[1])};
//latlng looks like '6.916333,79.861018' this
geocoder.geocode({'location': latlng}, function(results, status) {
if (status === 'OK') {
if (results[0]) {
map.setZoom(11);
var marker = new google.maps.Marker({
position: latlng,
map: map,
});
infowindow.setContent(results[0].formatted_address);
infowindow.open(map, marker);
} else {
// alert('No results found');
}
} else {
// alert('Geocoder failed due to: ' + status);
}
});
},
In my controller I pass the data as an array to the response in axios.post('gps/get-gps-location/'+this.allSelectedVehicles) this one.
Then I loop all those and set markers one by one. But what I need is to remove all markers from the google map and display the upcoming response data. It's not removing and shows the upcoming markers as well as existing markers also. So there are few markers on same point.
I tried most of the given examples and links on stackoverfow also but couldn't able to find a better solution. Your help is appreciated a lot.
Finally changed the previous code and can be used it as follows
getVehicleNumbers(vehicle_num){
this.loading = false;
if (vehicle_num.length == 0) {
this.allSelectedVehicles = 0;
} else {
this.allSelectedVehicles = vehicle_num;
}
axios.post('gps/get-gps-location/'+this.allSelectedVehicles)
.then(response => {
this.deleteMarkers();
for (let i = 0; i < response.data.data.length; i++) {
this.all_data = JSON.parse(response.data.data[i]);
this.longtitudes = this.all_data.item.pos.x;
this.latitudes = this.all_data.item.pos.y;
let longlatitude = {lat: this.latitudes, lng: this.longtitudes};
this.addMarker(longlatitude);
this.loading = true;
}
}).catch(Erors => {
this.loading = true;
});
},
addMarker(location) {
let marker = new google.maps.Marker({
position: location,
map: this.map,
});
this.markersArray.push(marker);
},
setMapOnAll(map) {
for (var i = 0; i < this.markersArray.length; i++) {
this.markersArray[i].setMap(map);
}
},
clearMarkers() {
this.setMapOnAll(null);
},
deleteMarkers() {
this.clearMarkers();
this.markersArray = [];
},
Once check the checkbox then it'll trigger getVehicleNumbers function. and through that the markers will be shown in the map. And if the checkbox is unchecked again the function will trigger and reset the map. then it'll show the new markers only.

Mark multiple locations in Google Map

I am using Google map api v3 to plot markers of location array. My script is
function OnSuccess(response) {
var markers = response.d.split('^^');
var latlng = new google.maps.LatLng(51.474634, -0.195791);
var mapOptions1 = {
zoom: 14,
center: latlng
}
var geocoder = new google.maps.Geocoder();
var infoWindow = new google.maps.InfoWindow();
var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions1);
for (i = 0; i < markers.length; i++) {
var data = markers[i];
geocoder.geocode({ 'address': data }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
title: data
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
(function (marker, data) {
// Attaching a click event to the current marker
google.maps.event.addListener(marker, "click", function (e) {
infoWindow.setContent(data);
infoWindow.open(map, marker);
});
})(marker, data);
}
where markers variable is bringing proper data, my test data is array of 5 elements
The Game Larder, 24 The Parade, Claygate, Surrey,KT10 0NU
24 The Parade, Claygate, Esher, Surrey KT10 0NU
Card Collection, 14 The Parade, Claygate, ESHER, KT10 0NU
16A The Parade, Claygate, ESHER, KT10 0NU
and same is coming into array markers however it is plotting only two markers. What could be wrong here
Solution
I was entering locations which are very close to each other e.g 1 and 2 point which gives same latlong hence mark as one place. I found latlong here. Thanks for answers btw :)
In page.aspx. insert tag <div id="map-canvas" ></div>
view source page.aspx and insert script into it>
var lis_marker = new Array();
for (i = 0; i < markers.length; i++) {
var data = markers[i];
geocoder.geocode({ 'address': data }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
lis_marker[i] = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
title: data
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
there are difference with your code:
1: var lis_marker = new Array();
2: lis_marker[i] = new google.maps.Marker({...});

Json Result MVC Controller to Google Map via Jquery

I have a problem because i want to use this Json Result that returns Json List but my problem is how should i call the json result that i will be using to geocode and add marker to my Google Maps ? I used getJson and its not functioning but i dont tried yet the .ajax function
Here is my sets of codes:
<script type="text/javascript">
var geocoder;
var map;
function initialize() {
var minZoomLevel = 4;
var zooms = 7;
geocoder = new google.maps.Geocoder();
map = new google.maps.Map(document.getElementById('map'), {
zoom: minZoomLevel,
center: new google.maps.LatLng(38.50, -90.50),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
// Bounds for North America
var strictBounds = new google.maps.LatLngBounds(
new google.maps.LatLng(15.70, -160.50),
new google.maps.LatLng(68.85, -55.90)
);
// Listen for the dragend event
google.maps.event.addListener(map, 'dragend', function () {
if (strictBounds.contains(map.getCenter())) return;
// We're out of bounds - Move the map back within the bounds
var c = map.getCenter(),
x = c.lng(),
y = c.lat(),
maxX = strictBounds.getNorthEast().lng(),
maxY = strictBounds.getNorthEast().lat(),
minX = strictBounds.getSouthWest().lng(),
minY = strictBounds.getSouthWest().lat();
if (x < minX) x = minX;
if (x > maxX) x = maxX;
if (y < minY) y = minY;
if (y > maxY) y = maxY;
map.setCenter(new google.maps.LatLng(y, x));
});
// Limit the zoom level
google.maps.event.addListener(map, 'zoom_changed', function () {
if (map.getZoom() < minZoomLevel) map.setZoom(minZoomLevel);
});
}
var iconBase = 'https://maps.google.com/mapfiles/kml/shapes/';
function codeAddress() {
var infowindow = new google.maps.InfoWindow();
$.getJson("Dashboard/DashboardIndex",null , function(address) {
$.each(address, function () {
var currVal = $(this).val();
address.each(function () {
geocoder.geocode({ 'address': currVal }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
icon: iconBase + 'man.png',
position: results[0].geometry.location,
title: currVal
})
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {
infowindow.setContent(currVal);
infowindow.open(map, marker);
}
})(marker, currVal));
address.push(marker);
}
else if (status == google.maps.GeocoderStatus.OVER_QUERY_LIMIT) {
setTimeout(codeAddress, 2000);
}
else {
alert("Geocode was not successful for the following reason: " + status);
}
});
});
});
});
return false;
}
window.onload = function () {
initialize();
codeAddress();
}
</script>
And my JsonResult at my Controller
public JsonResult LoadWorkerList()
{
var workerList = new List<Worker_Address>();
// check if search string has value
// retrieve list of workers filtered by search criteria
var list = (from a in db.Worker_Address
where a.LogicalDelete == false
select a).ToList();
List<WorkerAddressInfo> wlist = new List<WorkerAddressInfo>();
foreach (var row in list)
{
WorkerAddressInfo ci = new WorkerAddressInfo
{
ID = row.ID,
Worker_ID = row.WorkerID,
AddressLine1 = row.Address_Line1 + " " + row.Address_Line2+ " " +row.City + " "+ GetLookupDisplayValById(row.State_LookID),
LogicalDelete = row.LogicalDelete
};
wlist.Add(ci);
}
return Json(wlist.ToList().OrderBy(p => p.AddressLine1), JsonRequestBehavior.AllowGet);
}
Im thanking some who could help me in Advance :)
It's hard to guess where it goes wrong since you didn't post the JSON format and are getting errors (toLowerCase) of code you haven't posted. I think it's in the following area:
function codeAddress() {
var infowindow = new google.maps.InfoWindow();
$.getJson("Dashboard/DashboardIndex",null , function(address) {
console.log("full json object",address);//<--should show an array of objects
$.each(address, function () {
console.log(this);//<--here you can see what the JSON object is
var currVal = this["AddressLine1"];//<--guess from what your C# code looks like
//next each doesn't make much sense unless you have an array of arrays
// but the C# code makes json for a list (not a list of lists)
You can use IE for your console output but don't bother posting the output here because I can already tell you it's going to be [Object, object]. To get useful info you're going to have to use firefox with firebug or Chrome. To see the console you can press F12
The line:
setTimeout(codeAddress, 2000);
Could be optimized since now when you are making too many requests you'll fetch the entire address list again and start from the beginning instead of "waiting" for 2 seconds and continue where you were.
The following code:
map.setCenter(results[0].geometry.location);
Why set the center of the map within the loop? It'll just end up having the center of the last found address so you may as well do it outside the loop to set the center to last found address.

Javascript Loop - 2nd variable Not Displaying

Here is the code:
<script type="text/javascript">
var offender_locations = [
["10010", "xxxxx", 3],
["10001", "xxxxx", 2],
["10002", "zzzzz", 1]
];
for (i = 0; i < offender_locations.length; i++) {
var address = offender_locations[i][0];
var icon_img = offender_locations[i][1];
}
</script>
This is the output:
1) 10010 - zzzzz
2) 10001 - zzzzz
3) 10002 - zzzzz
AS you can see var address outputs the correct value, but *var icon_img* does always repeat the same value.
I am a Javascript beginner and I have tried all ways I can think of but I still get the same results.
P.S. I have pasted the full script here :
<script type="text/javascript">
var offender_locations = [
["10010", "offender_icon.png", 3],
["10001", "offender_icon.png", 2],
["10002", "visitor_icon.png", 1]
];
var myOptions = {
zoom: 10,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map"), myOptions);
var latlng = new google.maps.LatLng(0, 0);
for (i = 0; i < offender_locations.length; i++) {
var infowindow = new google.maps.InfoWindow();
var geocoder_map = new google.maps.Geocoder();
var address = offender_locations[i][0];
var icon_img = offender_locations[i][1];
geocoder_map.geocode({
'address': address
}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: map.getCenter(),
icon: icon_img
});
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {
infowindow.setContent(offender_locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
} else {
alert("The requested offender is not mappable !")
};
});
}
</script>
The markers in this script are all # the correct postal code, but they all show the same icon (visitor_icon.png) !
The problem is that you are creating a function in a loop. JavaScript has only function scope, not block scope. I.e. variables you create in a loop exist only once in the whole function, just the values changes per iteration.
At the time icon_img is evaluated (in the callback passed to geocode), the outer for loop already finished and icon_img has the value of the last iteration. It works for address because it is evaluated inside the loop, not later.
You have to 'capture' the current value of icon_img and you can do so by using an immediate function:
for (i = 0; i < offender_locations.length; i++) {
var infowindow = new google.maps.InfoWindow(),
geocoder_map = new google.maps.Geocoder(),
address = offender_locations[i][0],
icon_img = offender_locations[i][1];
(function(addr, img) { // <-- immediate function call
geocoder_map.geocode({'address': addr}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: map.getCenter(),
icon: img
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(addr);
infowindow.open(map, marker);
});
} else {
alert("The requested offender is not mappable !");
}
});
}(address, icon_img)); // <-- immediate function call
}
Maybe you hav to do this for even more variables... not sure.

Categories