I have three input array elements and two of them are hidden
defiend in javascript as:
var via_route = document.getElementsByName('via_route[]');
var viaLatitude = document.getElementsByName('via_route_lat[]'); --hidden in form
var viaLongitude = document.getElementsByName('via_route_long[]'); -- hidden elememnt
var viaAutocomplete = new google.maps.places.Autocomplete(inputw,{types:['address']});
//}
viaAutocomplete.addListener('place_changed', function(event) {
var place = viaAutocomplete.getPlace();
if (place.hasOwnProperty('place_id')) {
if (!place.geometry) {
// window.alert("Autocomplete's returned place contains no geometry");
return;
}
console.log('vlonh: '+vlength);
viaLatitude.value = place.geometry.location.lat();
viaLongitude.value = place.geometry.location.lng();
console.log('vlonh2: '+viaLongitude.value);
} else {
service.textSearch({
query: place.name
}, function(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
viaLatitude.value = results[0].geometry.location.lat();
viaLongitude.value = results[0].geometry.location.lng();
}
});
}
});
the value I want to get of all these three above arrays but only getting of via_route element
Edit:
for (var i = 0; i < via_route.length; i++) {
var inputw = via_route[i];
var viaAutocomplete = new google.maps.places.Autocomplete(inputw,{types:['address']});
//}
viaAutocomplete.addListener('place_changed', function(event) {
var place = viaAutocomplete.getPlace();
if (place.hasOwnProperty('place_id')) {
if (!place.geometry) {
// window.alert("Autocomplete's returned place contains no geometry");
return;
}
console.log('vlonh: '+i);
viaLatitude[i].value = place.geometry.location.lat();
viaLongitude[i].value = place.geometry.location.lng();
console.log('vlonh2: '+viaLongitude[i].value);
} else {
service.textSearch({
query: place.name
}, function(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
viaLatitude[i].value = results[0].geometry.location.lat();
viaLongitude[i].value = results[0].geometry.location.lng();
}
});
}
});
}
I think that since it is an array input, you can't directly assign value to it. You need to loop through the array and assign a value.
Example:
Here, I created two array input elements, and one is hidden.
<input type="text" name="arr1[]" style="display:none;">
<input type="text" name="arr2[]">
<p id="val1"></p>
<p id="val2"></p>
Now, I'll assign value through code:
var input1 = document.getElementsByName("arr1[]");
var input2 = document.getElementsByName("arr2[]");
for(var i=0; i < input1.length; i++){
input1[i].value = "10";
document.getElementById("val1").innerHTML = "arr1[] value is: "+input1[i].value;
}
for(var j=0; j < input2.length; j++){
input2[j].value = "20";
document.getElementById("val2").innerHTML = "arr2[] value is: "+input2[j].value;
}
It shows the values as 10,20. Here's the plunker
So, try looping as:
for(var i=0; i < viaLatitude.length; i++){
viaLatitude[i].value = place.geometry.location.lat();
}
for(var j=0; i < viaLongitude.length; j++){
viaLongitude[j].value = place.geometry.location.lng();
}
console.log(viaLatitude[0].value);
console.log(viaLongitude[0].value);
Related
Hi everyine please help me, I am trying to do a search filter on my vehicle tracking, the flow is, the servlet queries all data when there is no parameter filter is being sent by ajax. for example, I do have 5 data on query result so there will be 5 markers on the map, the ajax runs every two seconds so when I request a parameter for example only this spesific vehicle would be shown the query result would only be one, supposedly only marker on the screen, but the previous markers are not vanishing and keep up on the screen. how can I reset the markers into 0? can anyone please help me thanks! here is my code
<script type="text/javascript">
var values = [];
var map;
var markers = [];
function initMap()
{
var options = {
center: {lat: -33.890542, lng: 151.274856},
zoom: 4
};
map = new google.maps.Map(document.getElementById('map'), options);
var count = 0;
setInterval(function() {
getGps();
for(var i = 0; i <= markers.length; i++){
markers[i].setPosition(new google.maps.LatLng(values[count][1],values[count][2]));
count++;
}
}, 2000);
}
function removeMarkers(){
for(var i=0; i<markers.length; i++){
markers[i].setMap(null);
}
markers=[];
}
function getGps() {
xmlhttp.onreadystatechange=function() {
if( xmlhttp.readyState==4 && xmlhttp.status==200 ) {
removeMarkers();
var res = xmlhttp.responseText;
console.log(res);
var split1 = res.split("|");
if(split1[0] != "NOK"){
for(var i = 0; i < split1.length; i++){
var split2 = split1[i].split(",");
String(split2);
var holder1 = holder = [split2[0],split2[1],split2[2]];
values.push(holder1);;
var marker1 = marker = new google.maps.Marker({map: map, icon: 'images/mapvehicle.png', draggable: true});
markers.push(marker1);
}
}
}
};
xmlhttp.open("POST","GpsPost",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("txtTerminal="+document.getElementById('txtTerminal').value+"&txtMerchant="+document.getElementById('txtMerchant').value+"&txtAccount="+document.getElementById('txtAccount').value);
}
add this function and call it after this line .
if( xmlhttp.readyState==4 && xmlhttp.status==200 ) {
function removeMarkers(){
for(i=0; i<markers.length; i++){
markers[i].setMap(null);
}
markers=[]
values=[]
}
I have read many similar topics, but none of the answers seems to work for my case. I am working with Google Maps API to implement show/hide markers function using knockout data-binding. With show markers, there are no problems. But since I have to pass markers variable into hideMarkers function, I can't get this going.
Here is the html:
<div class="col-sm-6">
<input id="hide-listings" type="button" value="Hide Listings" class="btn1 btn-primary text-center" data-bind="click: hideMarkers">
</div>
Here is my ViewModel:
function viewModel() {
var self = this;
self.places = ko.observableArray(locations);
self.address = ko.observable();
self.city = ko.observable();
self.title = ko.observable();
self.id = ko.observable();
this.markers = ko.observable();
this.zaddress = ko.observable();
this.taddress = ko.observable();
this.paddress = ko.observable();
this.filter = ko.observable();
this.visiblePlaces = ko.computed(function() {
return this.places().filter(function(place) {
if (!self.filter() || place.title.toLowerCase().indexOf(self.filter().toLowerCase()) !== -1)
return place;
});
}, this);
//Zooms to a selected marker, open infowindow and displays current weather
self.zoomToPlace = function() {
// Initialize the geocoder.
var geocoder = new google.maps.Geocoder();
// Get the place.
var address = this.address;
var id = this.id;
var city = this.city;
var weatherAPIXU = "http://api.apixu.com/v1/current.json?key=453477e8eec14cbc805210143171706&q=" + city;
$.getJSON(weatherAPIXU, function(data) {
var forecast = data.current.temp_c;
$(".weather").html(forecast + '° C');
});
// Geocode the address/area entered to get the center. Then, center the map on it and zoom in
geocoder.geocode({
address: address,
}, function(results, status) {
map.setCenter(results[0].geometry.location);
map.setZoom(15);
google.maps.event.trigger(markers[id], 'click');
});
};
self.showListings = function() {
var bounds = new google.maps.LatLngBounds();
// Extend the boundaries of the map for each marker and display the marker
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(map);
bounds.extend(markers[i].position);
}
map.fitBounds(bounds);
};
// This function takes the input value in the find nearby area text input
// locates it, and then zooms into that area. This is so that the user can
// show all listings, then decide to focus on one area of the map.
self.zoomToArea = function() {
// Initialize the geocoder.
var geocoder = new google.maps.Geocoder();
// Get the address or place that the user entered.
var zaddress = this.zaddress();
// Make sure the address isn't blank.
if (zaddress === '') {
window.alert('You must enter an area, or address.');
} else {
// Geocode the address/area entered to get the center. Then, center the map on it and zoom in
geocoder.geocode({
address: zaddress,
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
map.setZoom(15);
} else {
window.alert(
'We could not find that location - try entering a more' +
' specific place.');
}
});
}
};
// This function allows the user to input a desired travel time, in
// minutes, and a travel mode, and a location - and only show the listings
// that are within that travel time (via that travel mode) of the location
self.searchWithinTime = function() {
// Initialize the distance matrix service.
var distanceMatrixService = new google.maps.DistanceMatrixService();
var taddress = this.taddress();
// Check to make sure the place entered isn't blank.
if (taddress === '') {
window.alert('You must enter an address.');
} else {
hideMarkers(markers);
// Use the distance matrix service to calculate the duration of the
// routes between all our markers, and the destination address entered
// by the user. Then put all the origins into an origin matrix.
var origins = [];
for (var i = 0; i < markers.length; i++) {
origins[i] = markers[i].position;
}
var destination = taddress;
var mode = document.getElementById('mode').value;
// Now that both the origins and destination are defined, get all the
// info for the distances between them.
distanceMatrixService.getDistanceMatrix({
origins: origins,
destinations: [destination],
travelMode: google.maps.TravelMode[mode],
unitSystem: google.maps.UnitSystem.IMPERIAL,
}, function(response, status) {
if (status !== google.maps.DistanceMatrixStatus
.OK) {
window.alert('Error was: ' + status);
} else {
displayMarkersWithinTime(response);
}
});
}
};
// This function fires when the user select "go" on the places search.
// It will do a nearby search using the entered query string or place.
self.textSearchPlaces = function() {
var bounds = map.getBounds();
var place = this.paddress();
hideMarkers(placeMarkers);
var placesService = new google.maps.places.PlacesService(map);
placesService.textSearch({
query: place,
bounds: bounds
}, function(results, status) {
if (status === google.maps.places.PlacesServiceStatus
.OK) {
createMarkersForPlaces(results);
}
});
};
// This function will loop through the listings and hide them all.
this.hideMarkers = function(markers) {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(null);
}
};
}
ko.applyBindings(new viewModel());
Please, advice me on how to best approach this issue, thank you!
If markers is this.markers then you dont need to pass the markers to the function as its available:
this.hideMarkers = function(markers) {
var m = markers == null ? this.markers : markers;
for (var i = 0; i < m.length; i++) {
m[i].setMap(null);
}
};
This means you can pass markers also to this function and if you dont it will default to your this.markers.
You can pass extra parameters in knockout like this also, if that is all your looking:
<input data-bind="click: hideMarkers.bind($data, markersYouWishtoHide)">
http://knockoutjs.com/documentation/click-binding.html
I have figured it out! The problem was that I was passing the value into the function inside the viewModel, but not in my click data-binding! The correct html:
<div class="col-sm-6">
<input id="hide-listings" type="button" value="Hide Listings" class="btn1 btn-primary text-center" data-bind="click: function() {hideMarkers(markers)}">
</div>
And the ViewModel function is simply:
self.hideMarkers = function() {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(null);
}
};
I am building an widget where user can upload an excel file and the places are get marked in the google map.
The following code works, but issue comes when i am reading an large excel file with 10k amount of data, the browser gets stuck. I am using a for loop and adding some timeout to get the data from the google api.
I pass the city name and get the latitude and longitude and mark it on the map.
Is there a better way i can implement?
Here is the code:
function googleMapsInit(widId, $scope, $http, $rootScope, $mdDialog) {
$scope.finish = function() {
var objIndex = getRootObjectById(widId, $rootScope.dashboard.widgets);
$mdDialog.hide();
document.getElementById('map').innerHTML = "";
//excel data
var array = JSON.parse($rootScope.json_string);
$scope.locationData = [];
//dividing it to chunks
var k,j,temparray,chunk = 8;
for (k=0,j=array.length; k<j; k+=chunk) {
temparray = array.slice(k,k+chunk);
var i;
//getting the longitude and latitude from the google geo api
for(i=0;i < temparray.length ; i++){
Geocode(temparray[i].PLACE_OF_ACCIDENT);
}
}
//sometimes data gets delayed
setTimeout(function(){ googleMap(); }, 5000);
};
function Geocode(address) {
var obj = {};
var geocoder = new google.maps.Geocoder();
geocoder.geocode({'address': address}, function(results, status) {
if (status === google.maps.GeocoderStatus.OK) {
obj = {
lat : results[0].geometry.location.G,
lng : results[0].geometry.location.K
};
setTimeout(function(){ $scope.locationData.push(obj); }, 100);
}
else if (status === google.maps.GeocoderStatus.OVER_QUERY_LIMIT) {
setTimeout(function() {
Geocode(address);
}, 100);
}
else if (status === google.maps.GeocoderStatus.ZERO_LIMIT) {
setTimeout(function() {
Geocode(address);
}, 100);
}
else {
}
});
}
function googleMap() {
var dataStore = $scope.locationData;
var array = JSON.parse($rootScope.json_string);
var map = new google.maps.Map(document.getElementById('map'),{
center: {lat: 7.85, lng: 80.65},
zoom: 6 });
var pinImageGreen = new google.maps.MarkerImage("http://maps.google.com/mapfiles/ms/icons/green-dot.png");
var pinImageBlue = new google.maps.MarkerImage("http://maps.google.com/mapfiles/ms/icons/blue-dot.png");
var marker = [];
var k;
for(k=0; k < array.length; k++){
marker[k] = new google.maps.Marker({
position: {lat: $scope.locationData[k].lat, lng: $scope.locationData[k].lng},
map: map,
title: array[k].PLACE_OF_ACCIDENT,
icon: pinImageGreen,
VEHICLE_TYPE: array[k].VEHICLE_TYPE,
VEHICLE_USAGE: array[k].VEHICLE_USAGE,
VEHICLE_CLASS: array[k].VEHICLE_CLASS
});
marker[k].addListener('click', function(data) {
var j;
for(j=0;j<array.length;j++){
if(($scope.locationData[j].lat == data.latLng.G) && ($scope.locationData[j].lng == data.latLng.K )){
document.getElementById("details").innerHTML =
array[j].PLACE_OF_ACCIDENT + "</br>" +
array[j].VEHICLE_TYPE + "</br>" +
array[j].VEHICLE_USAGE + "</br>" +
array[j].VEHICLE_CLASS + "</br>" ;
}
}
});
}
}
$scope.cancel = function() {
$mdDialog.hide();
};
}
One way to slightly improve performance is this: Instead of adding markers to the map one at a time, just create the markers array separately and then add them all at once to the map. Here is a sample code:
var markersData = [];
for (var i = 0; i < myArray.length; i++) {
var item = scope.myArray[i];
if (item.lat != undefined && item.lon != undefined) {
var icon = 'icon.png';
markersData.push({
lat: item.lat,
lng: item.lon,
title: 'xyz'
});
}
}
map.addMarkers(markersData);
By the way I have used "gmaps.js" for this which simplifies coding google maps, but you don't necessarily need it. The general idea is to avoid adding markers to the map inside the loop, one by one.
I'm having trouble getting my map to clear the clusters on a new search. Any ideas?
function clearLocations() {
//infoWindow.close();
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(null);
}
markers.length = 0;
// clear #side_bar bottom text
document.getElementById("side_bar").innerHTML = "";
// clear .alertBox text
$('.alertBox').html('');
}
function searchLocationsNear(center) {
clearLocations();
var searchUrl = 'phpsqlsearch_genxml.php?lat=' + center.lat() + '&lng=' + center.lng();
downloadUrl(searchUrl, function (data) {
var xml = parseXml(data);
var markerNodes = xml.documentElement.getElementsByTagName("marker");
if (markerNodes.length > 0) {
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < markerNodes.length; i++) {
var name = markerNodes[i].getAttribute("name");
var address = markerNodes[i].getAttribute("address");
var distance = parseFloat(markerNodes[i].getAttribute("distance"));
var category = markerNodes[i].getAttribute("category");
var latlng = new google.maps.LatLng(
parseFloat(markerNodes[i].getAttribute("lat")),
parseFloat(markerNodes[i].getAttribute("lng")));
// createOption(name, distance, i);
createMarker(latlng, name, address, category);
bounds.extend(latlng);
}
map.fitBounds(bounds);
var markerclusterer = new MarkerClusterer(map, markers);
// markerclusterer.setMap(null);
makeSidebar();
} else {
$('.alertBox').html('Sorry, there are no jobs that are close to your location.');
}
});
}
You should try this :
if (markers) {
for (i in markers) {
markers[i].setMap(null);
}
markers = [];
markerclusterer.clearMarkers()
}
According to the docs the clusterer can be clear with clearMarkers() method.
UPDATE
Call clear only when we have already create the MarkerClusterer.
if(markerclusterer)
{
clearLocations();
}
I am new to JavaScript.
Writing a script that uses GooogleMaps API
Working OK. Get Lat Lngs from Database, Make markers, put on Map.
Decided to move a function call up a level, (it was in the OnSuccess method of a PageMethod call). Stopped working.
Put in alerts to diagnose. Starts working.
Narrowed down to having alert at top of called function MakeLatLngs().
MakeLatLngs code appears to execute regardless of alert being present or commented out.
It is just that the map displays with alert statement in and doesn't display with alert statement commented out.
The alert is just text and not using any variable. So I am at a loss to understand what is going on here.
The same thing is happening in the function that draws the map DrawMap(). I put an informative alert at the start of the function and the map draws. Leave it out and the map doesn't.
Any clues as to what is going on would be appreciated?
The script is below.
Flow starts at function Initialise at bottom of script.
thanks
var myPositions = [];
var myRoutes = [];
var myString = [];
var myLatLngs = [];
var myTitles = [];
var NumPoints;
var map;
var poly;
var RouteName;
var myMarkers = [];
var myMapCentre = new google.maps.LatLng(-41.2954168187213, 174.767133718655);
function DrawMap() {
alert("Generating Points for " + RouteName);// Need this to display
var thisLatLng = myLatLngs[0];
var myOptions = {
zoom: 8,
center: thisLatLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map_canvas'),
myOptions);
MakeMarkers();
RouteLine();
}
function OnSuccess1(response) {
myPositions = new Array();
myString = response;
NumPoints = response.length;
for (var i = 0; i < NumPoints; i++) {
myPositions[i] = response[i];
}
}
function OnError1(response) {
}
function Marker()
{
this.meterId=0;
this.latLng="";
}
function OnSuccess(response) {
myPositions = new Array();
myString = response;
NumPoints = response.length;
alert("Numpoints is " + NumPoints);
for (var i = 0; i < NumPoints; i++) {
myPositions[i] = response[i];
}
alert("Exiting OnSuccess");
//MakeLatLngs(); //ORIGINAL POSITION OF LATLNG CALL
return true;
}
function setRoute() {
RouteName = prompt(' What route?', '');
}
function OnError(error) {
alert("In Error");
}
function RouteLine() {
var polyOptions = {
strokeColor: '#000000',
strokeOpacity: 1.0,
strokeWeight: 3
}
poly = new google.maps.Polyline(polyOptions);
poly.setMap(map);
var path = poly.getPath();
for (var i = 0; i < NumPoints; i++) {
path.push(myLatLngs[i]);
}
}
function MakeLatLngs() {
alert("You need me now " );//Got to have this to display OK when called from LoadData
myLatLngs = new Array();
for (var i = 0; i < NumPoints; i++) {
var sMarker = myPositions[i];
var SeqPos = sMarker.indexOf(";");
var latLngPos = sMarker.indexOf(";", SeqPos + 1);
var marker = sMarker.substring(0, latLngPos);
//alert("Marker is " + marker);
//var Seq = sMarker.substring(latLngPos + 1, SeqPos - latLngPos);
myTitles[i] = marker;
//alert("MeterId is " + marker);
var sLatLng = sMarker.substring(latLngPos + 1)
//alert("SLatLng is " + sLatLng);
var pos = sLatLng.indexOf(",");
//alert("pos is " + pos);
var sLat = sLatLng.substring(0, pos);
//alert("sLat is " + sLat);
var sLng = sLatLng.substring(pos + 1, sLatLng.length - 1);
//alert("sLng is " + sLng);
var lat = parseFloat(sLat);
var lng = parseFloat(sLng);
//alert("Lat is " + lat + " Long is " + lng);
if (!isNaN(lng) && !isNaN(lat) && lat != 0 && lng != 0 ) {
var latlng = new google.maps.LatLng(lat, lng);
myLatLngs[i] = latlng;
}
}
alert("Exiting MakeLatLngs")
}
function MakeMarkers() {
for (var i = 0; i < NumPoints; i++) {
var sTitle = "MyValue " + i;
var marker = new google.maps.Marker({
position: myLatLngs[i],
map: map,
title: myTitles[i]
});
}
}
function LoadData() {
setRoute();//Get the desired route from the user
PageMethods.GetMarkers(RouteName, OnSuccess, OnError);
MakeLatLngs(); //Works here ONLY WHEN AN ALERT IS FIRST LINE in FUNCTION. Orginal call was at end of OnSuccess
//PageMethods.GetRouteBoundaries(OnSuccess1, OnError1);
return false;
}
function initialize() {
LoadData();
DrawMap();
}
google.maps.event.addDomListener(window, 'load', initialize);//yes you do need this with or without <body onload="initialise">
The reason is that your PageMethods.GetMarkers is asynchronous, so the data hasn't loaded when you invoke DrawMap. I guess when you use the alert, it pauses execution long enough for the data to load. Put the DrawMap method inside the OnSuccess of the page method, and that should solve the problem.