I am trying to add google maps to my web page, the web page has div with id of radar with width specified. I get coordinates from a second page using jquery ajax method, and plot them on the map using Marker. But only the last marker is displayed nothing else is displayed.
var global = new Array();
$(document).ready(function () {
console.log("ready!");
if ($("#StartingDate").val() != "") {
var start = $("#StartingDate").val();
var end = $("#EndingDate").val();
var id = $("#UserId").val();
$.ajax({
url: "GetData.aspx?StartingDate=" + start + "&EndingDate=" + end + "&UserId=" + id, async: false, success: function (result) {
var resp = result.split(",");
for (x = 0; x < resp.length - 1; x++) {
var cor = resp[x].split(";");
var lat = cor[0];
var lon = cor[1];
var date = cor[2]
var temp = [lat, lon, date];
global.push(temp);
}
}
});
}
});
$(document).ajaxComplete(function () {
var myLatlng = new google.maps.LatLng(-25.363882, 131.044922);
var mapOptions = {
zoom: 4,
center: myLatlng
}
var map = new google.maps.Map(document.getElementById("radar"), mapOptions);
for (var i = 0; i < global.length; i++) {
console.log(global[i]);
var marker = new google.maps.Marker({
position: new google.maps.LatLng(parseFloat(global[i][0]),parseFloat(global[i][1])),
title: global[i][2]
});
marker.setMap(map);
}
});
After the ajax call succeeds my variable named global is filled like this:
global = [
[
0: "33.622835",
1: "73.062932",
2: "16/06/2015 1:17:24 AM"
],....
];
Edit: Turns out you have to set the .ajaxComplete handler before you make the ajax request since you have set async to false.
Here is a working example.
I would suggest saving the markers in an array if you intend to use the markers later on(i.e.: move them, or remove them).
Only the last marker is displayed because you override it every time. What you need to do is save the marker in an array.
What i would do is create a function addMarker which creates a marker with the given coordinates and a title and returns it.
This would look something like this:
function addMarker(title, x, y, map){
var marker = new google.maps.Marker({
position: new google.maps.LatLng(x,y),
map: map,
title: title
});
return marker;
}
This function should be called where you currently are setting the marker in the for-loop:
for (var i = 0; i < global.length; i++) {
console.log(global[i]);
markerArray[i] = addMarker(global[i][2], global[i][0], global[i][1], map);
}
markerArray needs to be a global array like global.
Related
I scraped data from Json and containing arrays in queryLat/queryLng after that I create another function initMap also bind it to google script. But I having hard to time passing queryLat and queryLng into initMap. "queryLat is not defined" pops up. How I can pass those to initMap.
var queryLat = [];
var queryLng = [];
#foreach($estates as $est)
var result = $.getJSON({
url: 'https://maps.googleapis.com/maps/api/geocode/json?address={{$est->address}}&key={{env('GOOGLE_MAPS_API')}}'
});
result.done(function(data) {
queryLat = data.results[0].geometry.location.lat;
queryLng = data.results[0].geometry.location.lng;
});
#endforeach
function initMap()
{
var options =
{
zoom : 10,
center : {lat:34.652500, lng:135.506302}
}
var map = new
google.maps.Map(document.getElementById("map"), options);
for (var i = 0; i < queryLat.length; i++)
{
var newMarker = new google.maps.Marker
({
position: {lat: queryLat[i], lng: queryLng[i]} ,
map: map
});
}
}
For multiple markers if you are defining arrays globally then you have to push your lat and long values in array and also need to update the marker variable to display diferent markers.. Hope it helps you to get the multiple markers.
var queryLat = [];
var queryLng = [];
#foreach($estates as $est)
var result = $.getJSON({
url: 'https://maps.googleapis.com/maps/api/geocode/json?address={{$est->address}}&key={{env('GOOGLE_MAPS_API')}}'
});
result.done(function(data) {
queryLat.push(data.results[0].geometry.location.lat);
queryLng.push(data.results[0].geometry.location.lng);
});
#endforeach
function initMap()
{
var options =
{
zoom : 10,
center : {lat:34.652500, lng:135.506302}
}
var map = new
google.maps.Map(document.getElementById("map"), options);
for (var i = 0; i < queryLat.length; i++)
{
var new_marker_str = "newMarker"+i;
new_marker_str = new google.maps.Marker
({
position: {lat: queryLat[i], lng: queryLng[i]} ,
map: map
});
}
}
You Should define your variables queryLat and queryLng globally where your script starts.
<script type="text/javascript">
var queryLat;
var queryLng;
#foreach($estates as $est)
var result = $.getJSON({
url: 'https://maps.googleapis.com/maps/api/geocode/json?address={{$est->address}}&key={{env('GOOGLE_MAPS_API')}}'
});
result.done(function(data) {
queryLat = data.results[0].geometry.location.lat;
queryLng = data.results[0].geometry.location.lng;
});
#endforeach
function initMap()
{
var options =
{
zoom : 12,
center : {lat:34.652500, lng:135.506302}
}
var map = new
google.maps.Map(document.getElementById("map"), options);
var marker = new
google.maps.Marker
({
position: {lat: queryLat, lng: queryLng},
map: map
});
}
The problem is in this code:
url: 'https://maps.googleapis.com/maps/api/geocode/json?address={{$est->address}}&key={{env('GOOGLE_MAPS_API')}}'
You have enclosed the string with apostrophes, but the string contains apostrophes too.
Use this instead:
url: "https://maps.googleapis.com/maps/api/geocode/json?address={{$est->address}}&key={{env('GOOGLE_MAPS_API')}}"
I have a big problem with Google Maps Api and jQuery.
I need get markers from XML file, and show on map.
This is page with map:
http://szymonnosal.pl/sandbox/bsk/
And my code:
I initialize map:
var mapa; // obiekt globalny
var dymek; // okno z informacjami
var networks = [];
var locations = [];
function mapaStart()
{
var wspolrzedne = new google.maps.LatLng(50.0157021545812, 19.9094574787954);
var opcjeMapy = {
zoom: 15,
center: wspolrzedne,
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDefaultUI: true,
navigationControl: true,
mapTypeControl: true
};
mapa = new google.maps.Map(document.getElementById("mapka"), opcjeMapy);
dymek = new google.maps.InfoWindow();
loadNetworks();
google.maps.event.addListener(mapa,'click',function(){
resetLocations();
});
}
In loadNetwork() I load marker from XML file, I using jQuery:
function loadNetworks()
{
$.get('net.xml',function(xml){
$(xml).find("network").each(function(){
var lat = parseFloat($(this).find("lat").text());
var lon = parseFloat($(this).find("lon").text());
var icon_url = $(this).find("icon").text();
var SSID = $(this).find("SSID").text();
var BSSID = $(this).find("BSSID").text();
var AuthMode = $(this).find("AuthMode").text();
var Frequency = $(this).find("Frequency").text();
//alert(lat+' '+lon+' '+icon_url+' '+SSID+' '+BSSID+' '+AuthMode+' '+Frequency);
var marker = addNetwork(lat,lon,icon_url,SSID,BSSID,AuthMode,Frequency);
alert(marker.txt); // <- marker is correct object, because in alert pop-up is text from marker.
});
});
}
And in addNetwork I add marker on map.
function addNetwork(lat,lon,icon_url,SSID,BSSID,AuthMode,Frequency)
{
var size = new google.maps.Size(30,23);
var start_point = new google.maps.Point(0,0);
var start_hook = new google.maps.Point(15,12);
var icon = new google.maps.MarkerImage(icon_url, size, start_point, start_hook);
var marker = new google.maps.Marker(
{
position: new google.maps.LatLng(lat,lon),
title: BSSID,
icon: icon,
map: mapa
}
);
marker.txt = 'BSSID: '+BSSID+'<br/>SSID: '+SSID+'<br />AuthMode: '+AuthMode+'<br />Frequency: '+Frequency;
google.maps.event.addListener(marker,"click",function()
{
dymek.setPosition(marker.getPosition());
dymek.setContent(marker.txt);
dymek.open(mapa);
});
return marker;
}
If i use other function to load XML, it's correct:
function loadNetworks()
{
jx.load('getNetwork.php', function(xml)
{
var markery = xml.getElementsByTagName("network");
for(var i=0; i<markery.length; i++)
{
var lat = parseFloat(markery[i].attributes.getNamedItem("lat").nodeValue);
var lon = parseFloat(markery[i].attributes.getNamedItem("lon").nodeValue);
var ikona_url = markery[i].attributes.getNamedItem("ikona").nodeValue;
var SSID = markery[i].attributes.getNamedItem("SSID").nodeValue;
var BSSID = markery[i].attributes.getNamedItem("BSSID").nodeValue;
var AuthMode = markery[i].attributes.getNamedItem("AuthMode").nodeValue;
var Frequency = markery[i].attributes.getNamedItem("Frequency").nodeValue;
var marker = addNetwork(lat,lon,ikona_url,SSID,BSSID,AuthMode,Frequency);
}
alert('Wczytano '+markery.length+' markerów z pliku networks.xml');
},'xml','get');
}
jx is function from: http://www.openjs.com/scripts/jx/
Do You have any idea, what is wrong in my code?
Looks to me like the icon_url is not defined. A test would be to change the marker definition to:
var marker = new google.maps.Marker(
{
position: new google.maps.LatLng(lat,lon),
title: BSSID,
// icon: icon,
map: mapa
});
This is on the live site:
var icon_url = jQuery(this).find("icon").text();
Not this (which is your posted code):
var ikona_url = markery[i].attributes.getNamedItem("ikona").nodeValue;
Your xml uses "ikona", and is the content of the element not an attribute.
<networks>
<network>
<lat>50.0158556853</lat>
<lon>19.9096229322</lon>
<SSID>untitled</SSID>
<BSSID>f0:7d:68:48:97:00</BSSID>
<AuthMode>[WPA-PSK-TKIP+CCMP][WPA2-PSK-TKIP+CCMP][ESS]</AuthMode>
<Frequency>2447</Frequency>
<ikona>http://maps.google.com/intl/en_us/mapfiles/ms/micons/green.png"</ikona>
</network>
</networks>
Is there a way you can convert XML to JSON as returned data?
If yes, then try vMap.
vMap is a lightning jQuery plugin with HTML 5 that makes Google Maps easy by sending a simple JSON Data Structure.
https://github.com/vhugogarcia/vMap
It helped me to solve a lot the markers problem with Google Maps, but also adds the feature for listing the locations if needed.
Feel free to modify it as your needs.
I'm trying to update a marker in real time on a Google Map. I need a marker for the starting location and then as the location changes (the user moves) a polyline will be drawn and a marker will show the current location. So, for each user there will be two markers; one showing the start location and one that keeps updating and showing the current location.
I can get the lines drawn and the start marker to work, but with this code each time the location changes, a new marker is placed instead of the old one being updated. I'm trying to use setPosition(); but it doesn't seem to work. Any thoughts?
function initialize() {
var myLatlng = new google.maps.LatLng(39, -86);
var myOptions = {
zoom: 6,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
}
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var loc = {};
var mark = {};
var markers = {};
$(function () {
$(document).ready(function(){
setInterval(function(){
$.ajax({
url: 'api.php', //the script to call to get data
//data: "",
dataType: 'json', //data format
success: function(data){ //on recieve of reply
var user_id = data[0];
var lati = data[1]; //get id
var longi = data[2]; //get name
var myLatlngt = new google.maps.LatLng(lati, longi);
if (typeof loc[user_id] === 'undefined') {
loc[user_id] = [];
}
//if (typeof markers[user_id] === 'undefined') {
//markers[user_id] = [];
//}
if (typeof mark[user_id] === 'undefined') {
mark[user_id] = myLatlngt;
}
loc[user_id].push(myLatlngt);
//markers[user_id].push(myLatlngt);
var marker1;
var x;
for (x in loc) {
var polyline = new google.maps.Polyline({
map: map,
path: loc[x],
strokeColor: "#FF0000",
strokeOpacity: 1.0,
strokeWeight: 2
});
polyline.setMap(map);
///location variables
var start_loc = loc[user_id];
var start_marker = start_loc[0]; //start location of given user
var current_loc = start_loc[start_loc.length -1]; //last known location of given user
//set the start marker
var marker = new google.maps.Marker({
position: start_marker,
title: user_id
});
marker.setMap(map);
//update the current location marker
if (marker1 != null) {
marker1.setPosition(current_loc);
}
else {
marker1 = new google.maps.Marker({
position: current_loc,
map: map
});
}
}
//console.log('location :::', x);
console.log('Marker: ', mark);
}
});
}, 1000);
});
});
}
Try declaring your marker1 variable (var marker1;) outside the function to make it global (scope). Right after var markers = {}; should do it. Let me know if this does not work, and I will look in to it deeper.
I have this JavaScript which should loop through my XML and get my data.
Here is the javascript code I have:
function load() {
var map = new google.maps.Map(document.getElementById("map"), {
zoom: 13,
mapTypeId: 'roadmap'
});
var infoWindow = new google.maps.InfoWindow;
var line =[];
downloadUrl("exportintoxml2.php", function(data) {
var xml = data.responseXML;
var devs = xml.documentElement.getElementsByTagName("DEVS"),
data = {};
for (var n = 0; n < devs.length; n++) {
var dev = devs[n],
markers = dev.getElementsByTagName("marker"),
dev_id = dev.getAttribute('DEVS');
data[dev_id] = [];
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("USER");
var imei = markers[i].getAttribute("IMEI");
var gsm1 = markers[i].getAttribute("GSM1");
var devices = markers[i].getAttribute("DEVS");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("LAT")),
parseFloat(markers[i].getAttribute("LON")));
var html = "<b>" + name + "</b> <br/>" + imei;
var icon = customIcons[devices] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon,
shadow: icon.shadow
});
bindInfoWindow(marker, map, infoWindow, html);
data[dev_id].push = ({ 'point' : point });
line.push(data[1]);
}
}
map.setCenter(point, 16);
var polyline = new google.maps.Polyline({
path: line,
strokeColor: "#FF0000",
strokeOpacity: 1.0,
strokeWeight: 2
});
polyline.setMap(map);
});
}
I need a variable (or several variables) which contains all of the data for every DEV separately and I am not sure how to include it in this loop.
I need to be able to display different devices with different polylines without them being connected with each other.
How can this be solved?
You need a loop for devs.
var devs = xml.documentElement.getElementsByTagName("DEVS"),
data = {}; // for storing the data after extraction
for ( var n = 0; n < devs.length; n++ ) {
var dev = devs[n],
markers = dev.getElementsByTagName("marker"),
dev_id = dev.getAttribute('devs');
data[dev_id] = [];
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("USER");
var data1 = markers[i].getAttribute("DATA1");
var data2 = markers[i].getAttribute("DATA2");
var devs2 = markers[i].getAttribute("DEVS");
data[dev_id].push({ 'name': name, 'data1': data1, 'data2': data2, 'devs': devs2 }); // store the data
}
}
In the line:
> var dev1 =
> xml.documentElement.getElementsByTagName("DEVS")[0];
getElementsByTagName returns a live NodeList. If you change it to:
var devs = xml.documentElement.getElementsByTagName("DEVS");
you can now loop over all the DEVS elements in the document.
As for storage of all the values, you already have them in the XML document so you might consider a function that returns the values as you need them, or get them all in a loop and store them in an object (but then you likely have to loop over the objet to get them back, just like you did in the first place to put them in there).
Hello
I'm looping over a JSON object and creating a new map marker for each item. After the marker is created, I push it to an array (var markers) for future manipulation. Problem is, when I try to access the array items (eg: console.log(markers[3])), I am given an "undefined" value.
Relevant code below:
var map;
var markers = [];
var activeFilters = [];
function initializeMap() {
var myLatlng = new google.maps.LatLng( 51.506873, -0.125141);
var myOptions = {
zoom: 14,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDefaultUI: true
}
map = new google.maps.Map(document.getElementById("location_map"), myOptions);
$.getJSON('../js/hotspots.json', function(data) {
var hotspots = data.scenes[0].hotspots;
$.each(hotspots, function(i) {
var lat = hotspots[i].latitude;
var lon = hotspots[i].longitude;
var point = new google.maps.LatLng(lat,lon);
var cat = hotspots[i].hotspottype;
var weburl = hotspots[i].weburl;
var marker = addMarker(point,cat,weburl);
});
});
}
function addMarker(point, cat, weburl) {
var markerUrl = weburl;
var marker = new google.maps.Marker({
position: point,
map: map
});
marker.category = cat;
markers.push(marker);
};
initializeMap();
console.log(markers[3]);
Any help would be greatly appreciated.
get json runs asynchronously. try this:
$.getJSON('../js/hotspots.json', function(data) {
var hotspots = data.scenes[0].hotspots;
$.each(hotspots, function(i) {
var lat = hotspots[i].latitude;
var lon = hotspots[i].longitude;
var point = new google.maps.LatLng(lat,lon);
var cat = hotspots[i].hotspottype;
var weburl = hotspots[i].weburl;
var marker = addMarker(point,cat,weburl);
});
console.log(markers);
});
Try to
console.log(markers[0]);
because looking at your code, there is just one element in markers array.
If you will put into that array 4 elements, then using markers[3] you will access fourth element.
try:
initializeMap();
setTimeout(function(){
console.log(markers[3]);
}, 10000);