Google Maps Max Markers - javascript

I'm not too great with javascript. Does anyone know how I can increase the number of markers displayed on Google Maps. I'm pulling about 300 locations from a MySQL database, but it's only plotting 50 or so.
Here's the code I'm using:
<script type="text/javascript">
//<![CDATA[
var iconBlue = new GIcon();
iconBlue.image = 'http://labs.google.com/ridefinder/images/mm_20_blue.png';
iconBlue.shadow = 'http://labs.google.com/ridefinder/images/mm_20_shadow.png';
iconBlue.iconSize = new GSize(12, 20);
iconBlue.shadowSize = new GSize(22, 20);
iconBlue.iconAnchor = new GPoint(6, 20);
iconBlue.infoWindowAnchor = new GPoint(5, 1);
var iconRed = new GIcon();
iconRed.image = 'http://labs.google.com/ridefinder/images/mm_20_red.png';
iconRed.shadow = 'http://labs.google.com/ridefinder/images/mm_20_shadow.png';
iconRed.iconSize = new GSize(12, 20);
iconRed.shadowSize = new GSize(22, 20);
iconRed.iconAnchor = new GPoint(6, 20);
iconRed.infoWindowAnchor = new GPoint(5, 1);
var customIcons = [];
customIcons["city"] = iconBlue;
function load() {
if (GBrowserIsCompatible()) {
var map = new GMap2(document.getElementById("map"));
map.addControl(new GSmallMapControl());
map.addControl(new GMapTypeControl());
map.setCenter(new GLatLng(47.614495, -122.341861), 1);
map.setMapType(G_SATELLITE_MAP);
GDownloadUrl("map-xml.php", function(data) {
var xml = GXml.parse(data);
var markers = xml.documentElement.getElementsByTagName("geolocation");
for (var i = 0; i < markers.length; i++) {
var time = markers[i].getAttribute("time");
var date = markers[i].getAttribute("date");
var city = markers[i].getAttribute("city");
var type = markers[i].getAttribute("city");
var point = new GLatLng(parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var marker = createMarker(point, time, date, city, type);
map.addOverlay(marker);
}
});
}
}
function createMarker(point, time, date, city, type) {
var marker = new GMarker(point, customIcons[type]);
var html = "<b>Time:" + time + "<br />Date:" + date + "<br/>City:" + city +"</b>";
GEvent.addListener(marker, 'click', function() {
marker.openInfoWindowHtml(html);
});
return marker;
}
//]]>
Thanks

I think you are looking for a Marker Manager.

I suspect that your markers are being plotted, but you're not seeing them for some reason.
Check that you're not plotting lots of markers at exactly the same location. If you plot one marker exactly on top of another it looks like one marker rather than of two.
Check that all your customIcons have image files in the right place. If there's no icon image you might not see anything.
customIcons[type] can fail if your "type" variable doesn't match one of your values. In particular the values are case specific. But if that's your problem you'd expect a Javascript error. Have you checked your error console?
Check that all your customIcons have a sensible size. If you omit the size parameter, the API will plot the image with zero size in some browsers.

I don't know of any limit on the markers allowed, I worked on a page with nearly 300 (http://bic-church.org/about/churches/map.asp). Mine, however, are loaded from a JSON file. Is it possible that you are experiencing some sort of timeout issue?
Edit: Additional thought: If you notice it consistently failing at a certain point, check the integrity of the data for that marker. You might find it is a bad lat/long or something.

Related

Google Maps adding marker from ajax using jquery

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.

Using computeDistanceBetween to work out the distance between the user's current location and a fixed point

I'm currently trying to code a simple web-app prototype for one of my university projects. I'm fairly new to Javascript and I'm having some trouble.
I've created a map that drops a marker at the user's current location, and a marker at a fixed point. Here is the Javascript so far:
var map;
function load() {
var myOptions = {
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map"), myOptions);
navigator.geolocation.getCurrentPosition(displayOnMap);
}
var pin;
function displayOnMap(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
var initialLocation = new google.maps.LatLng(latitude, longitude);
map.setCenter(initialLocation);
var marker = new google.maps.Marker({
map: map,
position: initialLocation,
});
loadMarkers();
}
function loadMarkers() {
var xmlMarkersRequest = new XMLHttpRequest();
xmlMarkersRequest.onreadystatechange = function() {
if (xmlMarkersRequest.readyState === 4) {
var xml = xmlMarkersRequest.responseXML;
var markersArray = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markersArray.length; i++) {
var id = Number(markersArray[i].getAttribute("id"));
var latitude = markersArray[i].getAttribute("latitude");
var longitude = markersArray[i].getAttribute("longitude");
var point = new google.maps.LatLng(
parseFloat(latitude),
parseFloat(longitude));
var marker2 = new google.maps.Marker({
map: map,
position: point,
zIndex: id
});
}
}
}
xmlMarkersRequest.open('GET', 'markers.xml', false);
xmlMarkersRequest.send(null);
}
Everything here works exactly how I want it to.
I'm just not sure how to use computeDistanceBetween to return the distance between the user's initial location (initialLocation), and the location of the marker.
The marker information is stored in an XML file because originally I planned to add more than one. But my site only needs one marker, so it's not a problem if I have to write the fixed marker's information into the Javascript instead.
I hope this question makes sense!
You need to load the geometry library
http://maps.googleapis.com/maps/api/js?key=YOURKEY&libraries=geometry
The distance between two points is the length of the shortest path between them. This shortest path is called a geodesic. On a sphere all geodesics are segments of a great circle. To compute this distance, call computeDistanceBetween() passing it two LatLng objects.
Example:
var a = new google.maps.LatLng(0,0);
var b = new google.maps.LatLng(0,1);
var distance = google.maps.geometry.spherical.computeDistanceBetween(a,b);
distance will be the distance in meters.

Google Maps Api v3, marker load from XML, not show on map

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.

Update marker in real time

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);
});
}

To get the position of draggable markers

I am using draggable markers in google maps. I have to get the position of markers after dragging because i have to store the new position of marker
The code is
var m = new GMarker(point,{draggable: true});
m.entry_id = id;
m.isMarker = true;
app.entries[id].marker = m;
Here is my example that will display the new location of the marker in and info-window at the new location after the marker has been dragged:
//assuming u have lat and long as latitude and longitude of the initial position
var location = new GLatLng(lat,long);
var marker = new GMarker(location, {draggable: true});
GEvent.addListener(marker, "dragstart", function() {
map.closeInfoWindow();
});
GEvent.addListener(marker, "dragend", function() {
var latlng = marker.getLatLng();
marker.openInfoWindowHtml("New Lat : " + latlng.lat() + ", New Long : " + atlng.lng() );
});
Am assuming you are using API version 2, the solution is a bit different for Version 3, but just a matter of change in the calling conventions sort of.

Categories

Resources