I need fetch the new position from json file which will be updated at regualr intervals in order to update it on the map without reloading the whole page repeatedly. How can I do without using Ajax
if (GBrowserIsCompatible()) {
//==add controls
var map = new GMap(document.getElementById("map"));
map.addControl(new GLargeMapControl());
map.addControl(new GMapTypeControl());
map.setCenter(new GLatLng(-29.870879, 30.977258),15);
var htmls = [];
var i = 0;
//create marker and set up infoWindow
function createMarker(point,ID,name) {
var marker = new GMarker(point);
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml(ID+"<br/>Name: " +name);
});
return marker;
}
process_Data = function(doc) {
//parse json file
var jsonData = eval('(' + doc + ')');
// ======== Plots the markers on Google Maps============
for (var i=0; i<jsonData.markers.length; i++) {
var point = new GLatLng(jsonData.markers[i].lat, jsonData.markers[i].lng);
var marker = createMarker(point,jsonData.markers[i].ID,jsonData.markers[i].name);
map.addOverlay(marker);
}
}
GDownloadUrl("points.json", process_Data);
}
var marker;
// every 10 seconds
setInterval(updateMarker,10000);
function updateMarker() {
$.post('/path/to/server/getPosition',{}, function(json) {
var LatLng = new google.maps.LatLng(json.latitude, json.longitude);
marker.setPosition(LatLng);
});
}
Related
I am developing an application which consist in bulky wastes' signalements where each citizen could inform authorities about the place to collect them.
Datas (addresses and coordinates) are stocked into firebase and I'm working on the display of markers in a google map.
Here is the code:
jQuery(function($) {
// Asynchronously Load the map API
var script = document.createElement('script');
script.src = "//maps.googleapis.com/maps/api/js?&callback=initialize";
document.body.appendChild(script);
});
function initialize() {
var map;
var bounds = new google.maps.LatLngBounds();
var mapOptions = {
mapTypeId: 'roadmap'
};
// Display a map on the page
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
map.setTilt(45);
markers: findMarkers();
console.log(markers);
console.log(markers.length);
// Info Window Content
var infoWindowContent = [
['<div class="info_content">' +
'<p>' + 'adresse' +'</p>' + '</div>'],
];
// Display multiple markers on a map
var infoWindow = new google.maps.InfoWindow(), marker, i;
// Loop through our array of markers & place each one on the map
for( i = 0; i < markers.length; i++ ) {
var position = new google.maps.LatLng(markers[i][1].lat(), markers[i][1].lng());
bounds.extend(position);
marker = new google.maps.Marker({
position: position,
map: map,
title: markers[i][0]
});
// Allow each marker to have an info window
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infoWindow.setContent(infoWindowContent[i][0]);
infoWindow.open(map, marker);
}
})(marker, i));
}
var boundsListener = google.maps.event.addListener((map), 'bounds_changed', function(event) {
this.setZoom(14);
google.maps.event.removeListener(boundsListener);
});
}
function findMarkers(){
markers = [];
var data = firebase.database();
var dataRef = firebase.database().ref("signalement/");
dataRef.on("child_added", function(data) {
var key = data.key;
const signalement = data.val();
const adresse = signalement.adresse;
const coordonnees = signalement.coordonnees;
var marker = [adresse, coordonnees];
markers.push( marker );
});
// Multiple Markers
return markers;
}
</script>
</head>
<body>
<div id="map_wrapper">
<div id="map_canvas" class="mapping"></div>
</div>
</html>
Problem comes from the console.log(markers.length); which is equal to 0 ! While the previous console.log(markers); shows the object.
Maybe a syntax error of var marker?
Anyway.
Someone to help me for this case?
Thanks
Looks like the problem is with the firebase data callback. Since you have set the callback for google map api callback=initialize the marker data is not ready from the firebase by the time it executes the function.
I would rather do something like this (keeping in mind that firebase callback takes longer than the google map script being loaded & map has dependency on the data from firebase).
jQuery(function($) {
// Asynchronously Load the map API
var script = document.createElement('script');
script.src = "//maps.googleapis.com/maps/api/js?&callback=findMarkers";
document.body.appendChild(script);
});
function initialize(markers) {
var map;
var bounds = new google.maps.LatLngBounds();
var mapOptions = {
mapTypeId: 'roadmap'
};
// Display a map on the page
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
map.setTilt(45);
console.log(markers);
console.log(markers.length);
// Info Window Content
var infoWindowContent = [
['<div class="info_content">' +
'<p>' + 'adresse' +'</p>' + '</div>'],
];
// Display multiple markers on a map
var infoWindow = new google.maps.InfoWindow(), marker, i;
// Loop through our array of markers & place each one on the map
for( i = 0; i < markers.length; i++ ) {
var position = new google.maps.LatLng(markers[i][1].lat(), markers[i][1].lng());
bounds.extend(position);
marker = new google.maps.Marker({
position: position,
map: map,
title: markers[i][0]
});
// Allow each marker to have an info window
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infoWindow.setContent(infoWindowContent[i][0]);
infoWindow.open(map, marker);
}
})(marker, i));
}
var boundsListener = google.maps.event.addListener((map), 'bounds_changed', function(event) {
this.setZoom(14);
google.maps.event.removeListener(boundsListener);
});
}
function findMarkers(){
markers = [];
var data = firebase.database();
var dataRef = firebase.database().ref("signalement/");
dataRef.on("child_added", function(data) {
var key = data.key;
const signalement = data.val();
const adresse = signalement.adresse;
const coordonnees = signalement.coordonnees;
var marker = [adresse, coordonnees];
markers.push( marker );
});
// send prepared marker array to map initialize function
intialize(markers);
}
I have a list of events that I display as markers on a map(its web application/site) and I would like to show only events in a certain distance (10 KM) from the user current location So, how can I combine this 2
//User Location
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(
function (position) {
var currentLatitude = position.coords.latitude;
var currentLongitude = position.coords.longitude;
// alert ("Latitude"+currentLatitude+"Longitude"+currentLongitude);window.mapServiceProvider(position.coords.latitude,position.coords.longitude);
// console.log(position);
}
);
}
//List of location from the Db.
var markers = #Html.Raw(Json.Encode(Model.UpcomingLectureGigs));
//Set All merkers on the map
window.onload = function (a) {
var mapOptions = {
center: new window.google.maps.LatLng(window.markers[0].Latitude, window.markers[0].Longitude),
zoom: 12,
mapTypeId: window.google.maps.MapTypeId.ROADMAP
};
var infoWindow = new window.google.maps.InfoWindow();
var map = new window.google.maps.Map(document.getElementById("dvMap"), mapOptions);
for (var i = 0; i < window.markers.length; i++) {
var data = window.markers[i];
var myLatlng = new window.google.maps.LatLng(data.Latitude, data.Longitude);
// console.log(data.Latitude, data.Longitude);
var marker = new window.google.maps.Marker({
position: myLatlng,
draggable: true,
animation: google.maps.Animation.DROP,
get map() { return map; }
});
(function (marker, data) {
window.google.maps.event.addListener(marker,
"click",
function (e) {
infoWindow.setContent(data
.Venue +
" " +
data.Genre.Name +
" " +
data.DateTime.toString("dd/mm/yy"));
//.toISOString().split("T")[0]);
// .format('MM/DD h:mm');
infoWindow.open(map, marker);
});
})(marker, data);
};
};
You can use a geometry library to calculate distance in meters between the user location and marker.
https://developers.google.com/maps/documentation/javascript/reference#spherical
The code snapshot to filter markers may be something like
var markers_filtered = markers.filter(function(marker, index, array) {
var myLatlng = new window.google.maps.LatLng(marker.Latitude, marker.Longitude);
return google.maps.geometry.spherical.computeDistanceBetween(userLatLng, myLatlng) < 10000;
});
for (var i = 0; i < markers_filtered.length; i++) {
//Your stuff here
}
You should add libraries=geometry parameter when you load Maps JavaScript API.
https://developers.google.com/maps/documentation/javascript/geometry
I've followed the PHP/MYSQL tutorial on Google Maps found here.
I'd like the markers to be updated from the database every 5 seconds or so.
It's my understanding I need to use Ajax to periodicity update the markers, but I'm struggling to understand where to add the function and where to use setTimeout() etc
All the other examples I've found don't really explain what's going on, some helpful guidance would be terrific!
This is my code (Same as Google example with some var changes):
function load() {
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(37.80815648152641, 140.95355987548828),
zoom: 13,
mapTypeId: 'roadmap'
});
var infoWindow = new google.maps.InfoWindow;
// Change this depending on the name of your PHP file
downloadUrl("nwmxml.php", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var host = markers[i].getAttribute("host");
var type = markers[i].getAttribute("active");
var lastupdate = markers[i].getAttribute("lastupdate");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var html = "<b>" + "Host: </b>" + host + "<br>" + "<b>Last Updated: </b>" + lastupdate + "<br>";
var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon,
shadow: icon.shadow
});
bindInfoWindow(marker, map, infoWindow, html);
}
});
}
function bindInfoWindow(marker, map, infoWindow, html) {
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
I hope somebody can help me!
Please note I have not tested this as I do not have a db with xml handy
First of all you need to split your load() function into a function that initializes the map & loads the markers on domready and a function that you will use later to process the xml & update the map with. This needs to be done so you do not reinitialize the map on every load.
Secondly you need to decide what to do with markers that are already drawn on the map. For that purpose you need to add them to an array as you add them to the map. On second update you have a choice to either redraw the markers (rebuild the array) or simply update the existing array. My example shows the scenario where you simply clear the old markers from the screen (which is simpler).
//global array to store our markers
var markersArray = [];
var map;
function load() {
map = new google.maps.Map(document.getElementById("map"), {
center : new google.maps.LatLng(37.80815648152641, 140.95355987548828),
zoom : 13,
mapTypeId : 'roadmap'
});
var infoWindow = new google.maps.InfoWindow;
// your first call to get & process inital data
downloadUrl("nwmxml.php", processXML);
}
function processXML(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
//clear markers before you start drawing new ones
resetMarkers(markersArray)
for(var i = 0; i < markers.length; i++) {
var host = markers[i].getAttribute("host");
var type = markers[i].getAttribute("active");
var lastupdate = markers[i].getAttribute("lastupdate");
var point = new google.maps.LatLng(parseFloat(markers[i].getAttribute("lat")), parseFloat(markers[i].getAttribute("lng")));
var html = "<b>" + "Host: </b>" + host + "<br>" + "<b>Last Updated: </b>" + lastupdate + "<br>";
var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
map : map,
position : point,
icon : icon.icon,
shadow : icon.shadow
});
//store marker object in a new array
markersArray.push(marker);
bindInfoWindow(marker, map, infoWindow, html);
}
// set timeout after you finished processing & displaying the first lot of markers. Rember that requests on the server can take some time to complete. SO you want to make another one
// only when the first one is completed.
setTimeout(function() {
downloadUrl("nwmxml.php", processXML);
}, 5000);
}
//clear existing markers from the map
function resetMarkers(arr){
for (var i=0;i<arr.length; i++){
arr[i].setMap(null);
}
//reset the main marker array for the next call
arr=[];
}
function bindInfoWindow(marker, map, infoWindow, html) {
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ? new ActiveXObject('Microsoft.XMLHTTP') : new XMLHttpRequest;
request.onreadystatechange = function() {
if(request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
setInterval(function() {
downloadUrl("conection/cargar_tecnicos.php", function(data) {
var xml = data.responseXML;
markers = xml.documentElement.getElementsByTagName("marker");
removeAllMarkers();
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("name");
var fecha = markers[i].getAttribute("fecha");
var id_android = markers[i].getAttribute("id_android");
var celular = markers[i].getAttribute("celular");
var id = markers[i].getAttribute("id");
var logo = markers[i].getAttribute("logo");
var type = markers[i].getAttribute("type");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var html = "<div class='infowindow'>"
+"<br/><div style='text-align:center;'><img src="+logo+"><br/>"
+"<b>" + name + "</b></div><br/>"
+"<br/><label><b>Celular:</b></label>" + celular+""
+"<br/><label><b>Id Android:</b></label>" + id_android+""
+"<br/><label><b>Fecha y Hora:</b></label>" + fecha+""
+"<br/><br/><div style='text-align:center;'><a><input style=';' id='pop' type='image' value='"+id+"' class='ASD' img src='img/vermas.png' title='Detalles'/></a></div></div>";
var icon = customIcons[type] || {};
marker[i] = new google.maps.Marker({
position: point,
icon: icon.icon,
shadow: icon.shadow,
title:name
});
openInfoWindow(marker[i], map, infoWindow, html);
marker[i].setMap(map);
}
});
},10000);
}
function removeAllMarkers(){// removes all markers from map
for( var i = 0; i < marker.length; i++ ){
marker[i].setMap(null);
}
}
Hey everybody! Im trying to use getLatLng() to geocode a list of postal/zip codes and store the generated point in the database to be placed on a map later. This is what I've got so far:
$(".geocodethis").click(function () {
var geocoder = new GClientGeocoder();
var postalCode = $(this).siblings(".postal").val();
var id = $(this).siblings(".id").val();
geocoder.getLatLng(postalCode, function (point) {
if (!point) {
alert(postalCode + " not found");
} else {
alert(point);
var serializedPoint = $.param(point);
//Geocode(id, point);
}
});
});
function Geocode(id, point) {
alert(point);
$.post("/Demographic/Geocode/" + id, point, function () {
alert("success?");
});
}
but I'm getting this.lat is not a function in my error console when i try to serialize the point object or use it in $.post()
From my research, I understand that geocoder.getLatLng() is asynchronous, how would that affect what I'm trying to do? I'm not running this code in a loop, and I'm trying to post the point using the anonymous callback function.
How can I save the information from point to use later?
Update
Creating a marker and trying to post that still results in the this.lat is not a function in the error console.
$(".geocodethis").click(function () {
var geocoder = new GClientGeocoder();
var postalCode = $(this).siblings(".postal").val();
var id = $(this).siblings(".id").val();
geocoder.getLatLng(postalCode, function (point) {
if (!point) {
alert(postalCode + " not found");
} else {
alert(point);
var marker = new GMarker(point);
$.post("/Demographic/Geocode/" + id, marker, function () {
alert("success?");
});
}
});
});
** Another Update **
I really need to save the geocoded address for later, even if I store the latitude/longitude values in my database and remake the marker when I'm ready to put it onto a map. Again, serializing or posting - seemingly using the point in any way other than in google maps functions gives the this.lat is not a function exception in my error log.
I'm using asp.net mvc - are there any frameworks out there that would make this easier? I really need help with this. Thanks.
If your stuck for 2 days maybe a fresh v3 start would be a good thing, this snipped does a similair job for me...
function GetLocation(address) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
ParseLocation(results[0].geometry.location);
}
else
alert('error: ' + status);
});
}
}
function ParseLocation(location) {
var lat = location.lat().toString().substr(0, 12);
var lng = location.lng().toString().substr(0, 12);
//use $.get to save the lat lng in the database
$.get('MatchLatLang.ashx?action=setlatlong&lat=' + lat + '&lng=' + lng,
function (data) {
// fill textboss (feedback purposes only)
//with the found and saved lat lng values
$('#tbxlat').val(lat);
$('#tbxlng').val(lng);
$('#spnstatus').text(data);
});
}
Have you tried this?
$(".geocodethis").click(function () {
var geocoder = new GClientGeocoder();
var postalCode = $(this).siblings(".postal").val();
var id = $(this).siblings(".id").val();
geocoder.getLatLng(postalCode, function (point) {
if (!point) {
alert(postalCode + " not found");
} else {
alert(point);
var marker = new GMarker(point);
map.addOverlay(marker);
obj = {lat: marker.position.lat(),
lng: marker.position.lng()};
$.post("/Demographic/Geocode/" + id, obj, function () {
alert("success?");
});
}
});
});
I haven't used V2 in a long time, so I'm not sure about the exact syntax, but the point is to create an object from the information you need (lat/lng) and serialize that.
Also, an upgrade to V3 is much recommended, if plausible.
You need to set a marker on the map, which takes a lat/long. You can save that info however you want or display immediately. (Code truncated for demo purpose)
map = new google.maps.Map(document.getElementById("Map"), myOptions);
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var marker = new google.maps.Marker({
position: results[0].geometry.location
});
marker.setMap(map);
}
}
UPDATE (FOR v2)
$(".geocodethis").click(function () {
var geocoder = new GClientGeocoder();
var postalCode = $(this).siblings(".postal").val();
var id = $(this).siblings(".id").val();
geocoder.getLatLng(postalCode, function (point) {
if (!point) {
alert(postalCode + " not found");
} else {
map.setCenter(point, 13);
var marker = new GMarker(point);
map.addOverlay(marker);
}
});
});
In V3 the coordinates must be first serialized as a string as shown by Arnoldiuss, before sending as json post data.
var lat = latlong.lat().toString().substr(0, 12);
var lng = latlong.lng().toString().substr(0, 12);
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<%# taglib prefix="s" uri="/struts-tags"%>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?key=AIzaSyDS1d1116agOa2pD9gpCuvRDgqMcCYcNa8&sensor=false"></script>
<script type="text/javascript">
function initialize() {
var latitude = document.getElementById("latitude").value;
latitude = latitude.split(",");
var longitude = document.getElementById("longitude").value;
longitude = longitude.split(",");
var locName = document.getElementById("locName").value;
locName = locName.split(",");
var RoadPathCoordinates = new Array();
RoadPathCoordinates.length = locName.length;
var locations = new Array();
locations.length = locName.length;
var infowindow = new google.maps.InfoWindow();
var marker, i;
var myLatLng = new google.maps.LatLng(22.727622,75.895719);
var mapOptions = {
zoom : 16,
center : myLatLng,
mapTypeId : google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
//To Draw a line
for (i = 0; i < RoadPathCoordinates.length; i++)
RoadPathCoordinates[i] = new google.maps.LatLng(latitude[i],longitude[i]);
var RoadPath = new google.maps.Polyline({
path : RoadPathCoordinates,
strokeColor : "#FF0000",
strokeOpacity : 1.0,
strokeWeight : 2
});
//Adding Marker to given points
for (i = 0; i < locations.length; i++)
locations[i] = [locName[i],latitude[i],longitude[i],i+1];
for (i = 0; i < locations.length; i++)
{marker = new google.maps.Marker({
position : new google.maps.LatLng(locations[i][1], locations[i][2]),
map : map
});
//Adding click event to show Popup Menu
var LocAddress ="";
google.maps.event.addListener(marker, 'click', (function(marker, i)
{ return function()
{
GetAddresss(i);
//infowindow.setContent(locations[i][0]);
infowindow.setContent(LocAddress);
infowindow.open(map, marker);
}
})(marker, i));}
function GetAddresss(MarkerPos){
var geocoder = null;
var latlng;
latlng = new google.maps.LatLng(latitude[MarkerPos],longitude[MarkerPos]);
LocAddress = "91, BAIKUNTHDHAAM"; //Intializing just to test
//geocoder = new GClientGeocoder(); //not working
geocoder = new google.maps.Geocoder();
geocoder.getLocations(latlng,function ()
{
alert(LocAddress);
if (!response || response.Status.code != 200) {
alert("Status Code:" + response.Status.code);
} else
{
place = response.Placemark[0];
LocAddress = place.address;
}
});
}
//Setting up path
RoadPath.setMap(map);
}
</script>
</head>
<body onload="initialize()">
<s:form action="mapCls" namespace="/">
<s:hidden key="latitude" id="latitude"/>
<s:hidden key="longitude" id="longitude"/>
<s:hidden key="locName" id="locName"/>
<div id="map_canvas" style="float:left;width:70%;height:100%"></div>
</s:form>
</body>
</html>
I am doing reverse Geocoding, and want address of marker using lat and longitude. M facing problem with function "GetAddresss()", line "geocoder.getLocations(latlng,function ()" is not working properly. what should I Do?
I've got the following problem with Googlemaps.
I've created a createMarker function which returns a marker which I publish with addOverlay(). This works perfect, the marker get shown but the only problem is the click event voor the marker, I want a infowindow which is populated with the 'I want this text to be published' text, instead it gets populated with a var called html which I set in the beginning of my code (var html = 'test';), I received earlier a message with 'html is not defined', this is why is set the html var. Every infowindow has the text 'test' in it. I've tried using updateInfoWindow() but that doesn't work, anyone familiar with this problem? I can supply you with the full source but I think the createMarker function should be enough.
function GM_load() {
map = new GMap2(document.getElementById("map"));
map.addControl(new GSmallMapControl());
map.addControl(new GMapTypeControl());
map.enableScrollWheelZoom();
map.setMapType(G_HYBRID_MAP);
geocoder = new GClientGeocoder();
GM_showItems();
}
function GM_showItems() {
GDownloadUrl("modules/Googlemaps/ajax/getItems.php", function(data, responseCode) {
var xml = GXml.parse(data);
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
//start
var itemid = markers[i].getAttribute('id');
var title = markers[i].getAttribute('name');
var address = markers[i].getAttribute('address');
var city = markers[i].getAttribute('city');
var x = 0;
if (geocoder) {
geocoder.getLatLng(address + ' ' + city,
function(point) {
if (!point) {
alert(address + ' ' + city + " not found");
} else {
x = x+1;
Marker = createMarker(point, x);
map.addOverlay(Marker);
}
}
);
}
}
});
}
function createMarker(latlng, number) {
var marker = new GMarker(latlng);
marker.value = number;
GEvent.addListener(marker,"click", function() {
map.openInfoWindowHtml(latlng,'i want this text to be published');
});
return marker;
}
Solved.
I overwrite var html. not perfect but it works.