I am a beginner to HTML and JavaScript . I read a text file which contains longitude and Latitude.
I read that text file and store it in 3 arrays. One contains longitude, One latitude and one contains ID.
Text file is like this: (you can store it for debugging purpose with my code below)
ID LONGITUDE LATITUDE
0 77.139305 28.795975
2 77.308929 28.486877
4 73.820680 18.464110
6 75.588783 26.599820
12 77.193575 28.559693
I read it and stored the column 1 , 2 and in col1, col2, col3 respectively.
Now the problem is the code below show me the marker on map only when I put the long lat manually but when I use the my column arrays it don't show me any marker whereas it shows map.
What i have in mind is to run this for loop in my code and it should render all the marker in the given map.(Yes it's true that i have stored all the Long and Lat and Id i can see on debugging).
My code is :
for (var i = 0; i <= array.length - 1; i++)
{
col1[j] = array[i];
col2[j] = array[i + 1];
col3[j] = array[i + 2];
var myLatlng = new google.maps.LatLng(col3[j], col2[j]);
var mapOptions =
{
zoom: 4,
center: myLatlng
}
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: 'Hello World!'
});
j++;
};
There are multiple things wrong with your code...
The map is declared inside the loop
Your split does not work correctly
The increments on your arrays to not step enough i
The Latitude and Longitude's were backwards in the marker definition
I have made the following edits and have a fiddle for you to look at so you can merge the code... http://jsfiddle.net/b4fz30vc/
function initialize() {
var data =
"ID LONGITUDE LATITUDE\r\n" +
"0 77.139305 28.795975\r\n" +
"2 77.308929 28.486877\r\n" +
"4 73.820680 18.464110\r\n" +
"6 75.588783 26.599820\r\n" +
"12 77.193575 28.559693\r\n";
var s2 = data.replace(/^.*$/, "").replace(/\r\n/g, " ");
var array = s2.split(/[ ]+/g);
var col1 = [];
var col2 = [];
var col3 = [];
var j = 0;
var mapOptions = {
zoom: 2,
center: new google.maps.LatLng(73, 23)
}
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
for (var i = 0; i <= array.length - 1; i++) {
col1[j] = array[i];
col2[j] = array[i++];
col3[j] = array[i++];
var myLatlng = new google.maps.LatLng(col3[j], col2[j]);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: 'Hello World! ' + col1[j]
});
j++;
}
}
initialize();
EDIT:
To comment on the var s2 = data.replace(/^.*$/, "").replace(/\r\n/g, " "); line.. with the first replace I am removing the header row and the second one removes the new lines.
You have to create a Marker array
var markers[];
Then in the loop you have to create to iterate over lat/longs, after marker is created put it into the array:
markers.push(marker);
In this way you can keep markers active...
You create new map for every marker, so your output contains only the last map with the last marker. Try to move this code:
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
before the for loop
btw in your for loop you should increment your iterator by 3
Related
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.
I need to assign 50 map markers for a google map. I don't want to have the (almost) same line of code 50 times. What is the best way to loop through this easily and optimize code?
var marker1 = new google.maps.Marker({position: new google.maps.LatLng(location1_latitude,location1_longitude),map: map1,title:location1});
var marker2 = new google.maps.Marker({position: new google.maps.LatLng(location2_latitude,location2_longitude),map: map1,title:location2});
var marker3 = ...
repeating to
var marker50 = new google.maps.Marker({position: new google.maps.LatLng(location50_latitude,location50_longitude),map: map1,title:location50});
you can use two arrays and iterate over them:
var location_latitude = [0,1,2,3,4,5] // all your latitudes
var location_longitude = [0,1,2,3,4,5] // all your longitudes
var location_titles = ['loc0','loc1','loc2','loc3','loc4','loc5']
var markers = []
for (var i = 0; i < location_latitude.length && i < location_longitude.length && i < location_titles.length; i++) {
markers[i] = new google.maps.Marker({position: new google.maps.LatLng(location_latitude[i],location_longitude[0]),map: map1,title:location_titles[i]});
}
you can also abstract lat, lng and title into an object:
var locations = [{lat: 0, lng: 0, title: 'latlng0'},{lat: 0, lng: 0, title: 'latlng0'}] // depending on how you get you're data, you'll want to adjust your loop's format so you don't have to manually convert it
var markers = []
for (var i = 0; i < locations.length; i++) {
var current = locations[i]
markers[i] = new google.maps.Marker({position: new google.maps.LatLng(current.lat,current.lng),map: map1,title:current.title});
}
I followed the example here to create an array of the markers that I put on my Google map on my web page.
I've looked for the past few hours at a lot of example both on the open web and here on SO and nothing I've tried works.
I need to:
1) save a Javascript array of Google Maps marker objects in a hidden input field
2) then retrieve the 'value' of the hidden input field and convert that back to the array of Marker objects so that I can remove these markers from the map
Here's my code, some is based on the Google Maps sample above:
theMarkersArray = new Array();
for(var i = 0; i < 5; i++)
{
marker = new google.maps.Marker({
position: myLatLng,
map: map,
icon: image,
shape: shape,
title: "aMarker",
zIndex: 1000});
theMarkersArray.push(marker);
}
theMarkersArrayField = document.getElementById('markersArray');
// I'm using Firefox v28.0, the following line of code halts code executing,
// I'm thinking that 'JSON.stringify()' is not defined for FF 28.0..?)
//theMarkersArrayField.value = JSON.stringify(theMarkersArray);
// this executes, but I don't think it's saving the array of Marker objects
// correctly
theMarkersArrayField.value = theMarkersArray;
alert("the theMarkersArray is: "+ theMarkersArray);
When I display the contents of theMarkersArrayField.value using alert(), it looks like this:
[object Object],[object Object],[object Object],[object Object],[object Object]
and when I try to convert theMarkersArrayField.value back into a Javascript array using either eval() or JSON.parse(), both fail.
var theMarkersArrayField = document.getElementById('markersArray');
// DOES NOT WORK
//var theMarkersArray = JSON.parse(theMarkersArrayField.value);
// THIS doesn't work either
//var theMarkersArray = eval(theMarkersArrayField.value);
// IS NOT AN ARRAY OF 'Marker' objects, just a text string it seems...?
var theMarkersArray = document.getElementById('markersArray').value;
// RETURNS '79' INSTEAD OF 5 (only 5 markers were stored in the array, not 79) --
// 79 is the count of characters in:
// [object Object],[object Object],[object Object],[object Object],[object Object]
var numMarkers = theMarkersArray.length;
I need to store an array of Marker objects in an array then save that array in a hidden field on the page, then later retrieve that from the hidden field, convert it back to an array of Marker objects -- what am I missing?
demo: http://jsfiddle.net/drA5k/
function addMarker(location) {
for(var i = 0; i < 5; i++) {
var marker = new google.maps.Marker({
position: location,
map: map
});
// of course if you need only the position you can avoid looping and just get
// marker.position.k and marker.position.A , this example dimostrate
// how to iterate and get data from the object and build a custom array...
for (var o in marker) {
if (typeof marker[o] === 'object') {
if (o === 'position') {
var position = marker[o];
markers.push({'k' : position.k, 'A' : position.A});
}
}
}
}
document.getElementById('markersArray').value = JSON.stringify(markers);
}
I create a store locator with this code
myData = JSON = $.parseJSON(msg);
var dist = [];//Array to hold distances
var geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': ''+origin2+', us'}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
myLatitud = results[0].geometry.location.lat();
myLongitud = results[0].geometry.location.lng();
origin1 = new google.maps.LatLng(myLatitud, myLongitud);
for (var i = 0; i < myData.length; i++){
var point = new google.maps.LatLng(myData[i].latitud,myData[i].longitud);
var distance = (google.maps.geometry.spherical.computeDistanceBetween(origin1, point)/1000).toFixed(2);
dist.push(distance);
}
var map = new google.maps.Map(document.getElementById('map-canvas'), {
zoom: 11,
center: new google.maps.LatLng(myLatitud, myLongitud),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var marker;
marker = new google.maps.Marker({
position: new google.maps.LatLng(myLatitud, myLongitud),//25.7889689 -80.22643929999998
//position: new google.maps.LatLng(25.7889689,-80.22643929999998),
map: map,
icon : originIcon
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
// infowindow.setContent(myData[i].store);
//infowindow.open(map, marker);
map.setZoom(10);
map.setCenter(marker.getPosition());
}
})(marker, i));
map.setCenter(marker.getPosition());
map.setZoom(10);
millas = params['millas'];
var result = [];//Array of definitive stores
for ( var i = 0; i < dist.length; i++) {
var kilometro = dist[i];
if (millas == "1" && kilometro < 8) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(myData[i].latitud, myData[i].longitud),
map: map,
icon : destinationIcon
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(myData[i].store);
infowindow.open(map, marker);
map.setZoom(12);
map.setCenter(marker.getPosition());
}
})(marker, i));
}
I'm trying to make a simple page that allows addresses from a mysql database to be converted to lat and long and then displayed as markers on a map.
Most of the code below comes from the google docs with the addition of some geocoder stuff.
I can successfully alert the correct coordinates (see line 48-53) but then I try to pass them into 'point' variable for google maps to create a marker but nothing appears on the map.
Can anyone see whats wrong with my code? I'm not familiar with Javascript so it could be something really fundamentally wrong.
Thanks
function load() {
geocoder = new google.maps.Geocoder();
map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(47.6145, -122.3418),
zoom: 3,
mapTypeId: 'roadmap'
});
var infoWindow = new google.maps.InfoWindow;
// Change this depending on the name of your PHP file
downloadUrl("phpsqlajax_genxml3.php", function(data) {
var coords;
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("name");
var address = markers[i].getAttribute("address");
var type = markers[i].getAttribute("type");
geocoder.geocode( { 'address': address}, function(results, status) {
var latpoint = parseFloat(results[0].geometry.location.lat());
var lngpoint = parseFloat(results[0].geometry.location.lng());
coords = latpoint + ', ' + lngpoint;
//alert(coords); //For Testing
});
var point = new google.maps.LatLng(coords);
var html = "<b>" + name + "</b> <br/>" + address;
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);
}
});
}
The LatLng object constructor is waiting for Number type. Here you give it a string with the concatened coordinates, wich is wrong.
Look at the doc here.
Try that instead :
var latpoint = parseFloat(results[0].geometry.location.lat());
var lngpoint = parseFloat(results[0].geometry.location.lng());
var point = new google.maps.LatLng(latpoint, lngpoint);
And please refer to the #Pekka 웃 comment to be sure people answer you next time.
I am having trouble clearing any existing polylines before displaying a new one. I've already tried more than 5 different methods (array length = 0, MVCArray clear, polylines.setMap(null), etc) that I found on the web. I am using google maps V3, and here's the code from my js file
// initialize the google map
var latlng = new google.maps.LatLng(37.775, -122.418333);
var myOptions = {
zoom: 11,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
// declare bounds object
var bounds = new google.maps.LatLngBounds();
// run the following functions when Routes dropdown box is changed
$("#routeID").change(function(){
// when JSON object is retrieved, delete existing overlays
deleteOverlays();
if ($("#routeID").val() > 0) {
// get JSON object from routestations.php (route information, lat, lon for stations on the selected route)
$.getJSON('includes/routestations.php',{'routeID':$("#routeID").val()}, function(routeInfoJSON){
// plot the new overlays
overlays(routeInfoJSON);
});
}
});
// delete overlays (markers, polylines) to "reset" the map before displaying other overlays
deleteOverlays = function() {
if (markersArray) {
for (i in markersArray) {
markersArray[i].setMap(null);
}
markersArray.length = 0;
}
}
// declare an empty array for markers
var markersArray = [];
//set infoWindow global
var infoWindow;
// Place layer objects (polylines, markers, etc) for the selected route
overlays = function(routeInfoJSON) {
// declare polylinesArray
var polylinesArray = [];
for(var i=0; i < routeInfoJSON.config.station.length; i++){
// create point, marker objects
var point = new google.maps.LatLng(parseFloat(routeInfoJSON.config.lat[i]),parseFloat(routeInfoJSON.config.lon[i]));
var marker = new google.maps.Marker({
position: point,
map: map,
title: routeInfoJSON.config.station[i]
});
// push marker into markersArray (for future removal purposes only)
markersArray.push(marker);
// push lat/lon into polylinesArray
polylinesArray.push(point);
// set the marker on the map
marker.setMap(map);
// set & display infoWindow content
(function(i, marker){
if(!infoWindow){
infoWindow = new google.maps.InfoWindow();
}
var html = '';
google.maps.event.addListener(marker, 'click', function() {
// get JSON object from routestations.php (route information, lat, lon for stations on the selected route)
$.getJSON('includes/schedule.php', function(schedJSON){
// look through the stations in the schedule to match it with the user-selected station
for (var n = 0; n < schedJSON.station.length; n++) {
// if we find the station in the JSON that matches the user-selected station, then execute -->
if (schedJSON.station[n].abbr == routeInfoJSON.config.station[i]){
var html = "<div id=infoWindow class=info>";
html = html + "<h3>Train Arrival Times for '" + schedJSON.station[n].name + "' Station</h3>";
// set html for inforWindow
for (var c = 0; c < schedJSON.station[n].eta.length; c++) {
html = html + "<strong>To " + schedJSON.station[n].eta[c].destination + ": ";
html = html + "</strong>" + schedJSON.station[n].eta[c].estimate + "<br /><br />";
}
html = html + "</div>";
}
}
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
});
})(i, marker);
// extend bound object with each LatLng
bounds.extend(point)
}
// Adjust the map to new bounding box
map.fitBounds(bounds);
// start polylines codes
var polyLine = new google.maps.Polyline({
path: polylinesArray,
strokeColor: routeInfoJSON.color,
strokeOpacity: 0.8,
strokeWeight: 5
});
// set polyline on map
polyLine.setPath(polylinesArray);
polyLine.setMap(map);
}
could you please help me figure it out?
Thank you!
hope this help
//global path
var path = null;
...
//create new polyline
var polyLine = new google.maps.Polyline({
path: polylinesArray,
strokeColor: routeInfoJSON.color,
strokeOpacity: 0.8,
strokeWeight: 5
});
//delete old
var prepath = path;
if(prepath){
prepath.setMap(null);
}
//new polyline
polyLine.setMap(this.map);
// assign toglobal var path
path = polyLine;