I'm trying to import markers from .js file into my Google Maps.
I use Google Maps Javascript API v3.
If the .js file has too many markers, the map doesn't show any marker.
When I delete some markers in .js file, the map shows all markers from .js file.
What's wrong with this?
I want to import 1,000 ~ 3,000 markers from .js file and show the markers only in the visible bound on the map.
Is there any limitation of the markers while reading .js file?
I don't use JQuery, node.js.
Do I have to callback function? Please help me.
Thanks in advance.
a.html
...
<script src="js/markers.js"></script>
...
<script type="text/javascript">
var mymap; // one map
...
function showMarker(eachLocations) {
// get the center of the map and zoom level
var new_center = mymap.getCenter();
defaultLat = new_center.lat();
defaultLon = new_center.lng();
var zoomLevel = mymap.getZoom();
var marker,i;
var pin_image_url = "/common/images/marker_img.png";
var myMarkerIcon;
var bounds = mymap.getBounds();
var ne = bounds.getNorthEast(); // LatLng of the north-east corner
var sw = bounds.getSouthWest(); // LatLng of the south-west corder
var nw = new google.maps.LatLng(ne.lat(), sw.lng());
var se = new google.maps.LatLng(sw.lat(), ne.lng());
// for each location
for (i = 0; i < eachLocations.length; i++) {
// custom marker
myMarkerIcon = new
google.maps.MarkerImage(pin_image_url,null,null,null,new
google.maps.Size(32,37));
if (eachLocations[i][1] >= se.lat() && eachLocations[i][1] <= nw.lat() && eachLocations[i][2] >= nw.lng() && eachLocations[i][2] <= se.lng()) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(eachLocations[i][1], eachLocations[i][2]),
map: mymap,
icon: myMarkerIcon
});
markers.push(marker);
// listner for marker
google.maps.event.addListener(marker, 'click', (function(marker, i) {
// click,dblclick,mouseup,mousedown,mouseout
return function() {
// if any infowindow has already shown, hides it and shows the new one
if (infowindow) infowindow.close();
// make the infoWindow of the first marker
infowindow = new google.maps.InfoWindow({
map: mymap,
position: new google.maps.LatLng(eachLocations[i][1], eachLocations[i][2])
});
infowindow.setContent('<div style="width:250px;text-align: center;font-size:10pt;font-family:Arial,Verdana;font-weight:bold";>'+eachLocations[i][0]+'</div>');
infowindow.open(mymap, marker);
}
})(marker, i));
} // end of if the location is in the bounds
} // end of for each locations
} // end of function
function initialize() {
var mapDiv=document.getElementById("mapholder");
var myOptions={
center:new google.maps.LatLng(defaultLat,defaultLon),
zoom:defaultZoomLevel,
mapTypeId:google.maps.MapTypeId.ROADMAP,
zoomControl: true, // by default
zoomControlOptions: {style: google.maps.ZoomControlStyle.LARGE},
mapTypeControl:false,
navigationControlOptions:
{style:google.maps.NavigationControlStyle.SMALL}
};
// make map instance
mymap=new google.maps.Map(mapDiv,myOptions);
// Create the DIV to hold the control and
// call the CenterControl() constructor passing in this DIV
var centerControlDiv = document.createElement('div');
var centerControl = new CenterControl(centerControlDiv, mymap);
centerControlDiv.index = 1;
mymap.controls[google.maps.ControlPosition.BOTTOM_LEFT].push( centerControlDiv);
getLocation();
google.maps.event.addListener(mymap, 'idle', function(ev){
var new_center = mymap.getCenter();
defaultLat = new_center.lat();
defaultLon = new_center.lng();
// you may have too many markers problem
// so, before sending array, you have to rearrange markers to show
var bounds = mymap.getBounds();
var ne = bounds.getNorthEast(); // LatLng of the north-east corner
var sw = bounds.getSouthWest(); // LatLng of the south-west corder
var nw = new google.maps.LatLng(ne.lat(), sw.lng());
var se = new google.maps.LatLng(sw.lat(), ne.lng());
var markers2show = [];
var lengthofarray = myLocations.length;
for (i=0;i<myLocations.length;i++) {
// limit the markers for the new bound
if (myLocations[i][1] >= se.lat() && myLocations[i][1] <= nw.lat() && myLocations[i][2] >= nw.lng() && myLocations[i][2] <= se.lng()) {
markers2show.push(myLocations[i]);
}
}
showMarker(markers2show);
});
// close the previous info window of marker when click the map
google.maps.event.addListener(mymap, 'click', function() {
infowindow.close();
});
showMarker(myLocations);
}
...
<body onload="initialize()">
...
js/markers.js
var myLocations = [
['A Location',37.007756,140.750864],
['B Location',37.111598,140.424843],
['C Location',36.881268,140.025215]
];
Related
Hi everyone i have a bout 500 addresses or so to be listed in Google maps , each address being grabbed from a filemaker database than grouped under a category person(employee name in the map) i'm using a function to geocode and i'm calling it every 10th time with a 10 sec
setimout, the problem is:
1- the page is very very slow with settimeout 10sec when you have to show 500 addresses( addresses can change any second never fixed addresses) is there a better way?
2- even with settimout set to call every 10 seconds, i still get sporadically OVER_QUERY_LIMIT , why does that happen, 10 seconds is along time.
here is the code:
<pre><script type="text/javascript">
var mapOptions = {
//center:myLatLng,
//zoom:15,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map-canvas"),
mapOptions);
//var contentString='<div id="google_info_window">I;m Here</div>';
//var infowindow = new google.maps.InfoWindow();
var infowindow = new google.maps.InfoWindow(
{
size: new google.maps.Size(150,50)
});
var addresses = new Array();
var gmarkers = [];
addresses = <?php echo json_encode($project_info); ?>;
console.log("Addresses: <pre>"+JSON.stringify(addresses));
<?php //foreach($project_info as $i => $val){?>
//addresses.push('<?php //echo $val; ?>');
<?php //}?>
var bounds = new google.maps.LatLngBounds();
i=1;
mySleepFunction();
function mySleepFunction()
{
var geocoder = new google.maps.Geocoder();
//var myLatLng = new google.maps.LatLng(30,-50);
//var contentString='<div id="google_info_window">I;m Here</div>';
//for(var i = 0; i<Object.keys(addresses).length; i++)
var show_message= document.getElementById('map_message');
show_message.style.display="block";
show_message.innerHTML ="<div>Loading Please Wait...</div>";
for (; i < 200; i++) {
if(i %10 == 0) {
setTimeout(geocoder.geocode({'address': addresses[i-1]['Address']}, makeCallback(i)),2000);
i++;
setTimeout("mySleepFunction()",9000);
break;
}
geocoder.geocode({'address': addresses[i-1]['Address']}, makeCallback(i));
if (i==199){
show_message.style.display = 'none';
}
}//For statement
function makeCallback(addressIndex) {
var i = addressIndex-1;
var geocodeCallBack = function(results, status) {
if (status != google.maps.GeocoderStatus.OK) {
console.log("Geocode was not successful for the following reason: " + status);
} else {
var p = results[0].geometry.location;
var address_formated = results[0].formatted_address;
var appraiser = addresses[i]['Staff'];
//var latlng = new google.maps.LatLng(p.lat,p.lng);
map.setCenter(p);
createMarker(map,address_formated,p,appraiser);
// sets the center point to be the p
//map.setZoom(10); // sets the zoom level
//bounds.extend(latlng);
// main.setMap(map, point, titles[i], bounds);
show(appraiser);
}
}
return geocodeCallBack;
}// fUNCTION MAKECALLBAC
}
//map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
map.fitBounds(bounds);
// map.panToBounds(bounds);
function createMarker(map,add,p,appraiser) {
var str = add;
var numb=str.indexOf(',');
//alert("position of:"+numb);
str = str.substr(0, numb+1) +"<br/>"+ str.substr(numb+1);
var contentString = '<div id="google_info_window" style="min-height:40px;height:auto;width:auto;"><strong>'+appraiser+'</strong><p style="margin:1px;padding:5px 1px 2px 1px">'+str+'</p></div>';
//var infowindow = new google.maps.InfoWindow();
var marker = new google.maps.Marker({
map: map,
title:appraiser,
position: p
});
marker.mycategory = appraiser;
gmarkers.push(marker);
//Open the infowindow
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
infowindow.setContent(contentString);
});
marker.setMap(map,bounds);
}
// == shows all markers of a particular category, and ensures the checkbox is checked ==
function show(appraiser) {
for (var i=0; i<gmarkers.length; i++) {
if (gmarkers[i].mycategory == appraiser) {
gmarkers[i].setVisible(true);
}
}
// == check the checkbox ==
var appraiser_id = appraiser.replace(/\s/g,"");
var apraiser_checkbox_id = appraiser_id+"_Checkbox";
document.getElementById(appraiser_id+"_Checkbox").checked = true;
}
// == hides all markers of a particular category, and ensures the checkbox is cleared ==
function hide(appraiser) {
for (var i=0; i<gmarkers.length; i++) {
if (gmarkers[i].mycategory == appraiser) {
gmarkers[i].setVisible(false);
}
}
// == clear the checkbox ==
var appraiser_id = appraiser.replace(/\s/g,"");
document.getElementById(appraiser_id+"_Checkbox").checked = false;
// == close the info window, in case its open on a marker that we just hid
infowindow.close();
}
function boxclick(box,appraiser) {
if (box.checked) {
show(appraiser);
} else {
hide(appraiser);
}
// == rebuild the side bar
}
// google.maps.event.addDomListener(window, 'load', initialize);
</script></pre>
http://plnkr.co/edit/Zd9GwG?p=preview
I am working on this google map + angular.js example . I want to change the location center dynamically depend on the variable .i.e. I want to make it dynamic center. Please suggest how to do this ?
I want to do some thing Like this.
// Code goes here
//Add the requried module 'angular-ui' as a dependency
angular.module('maptesting', ['ui.directives']);
function MapCtrl($scope) {
$scope.lat = 35.120922 ;
$scope.long = -89.97731 ;
var ll = new google.maps.LatLng($scope.lat, $scope.long);
$scope.mapOptions = {
center: ll,
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
//Markers should be added after map is loaded
$scope.onMapIdle = function() {
//alert("DF");
if ($scope.myMarkers === undefined){
var marker = new google.maps.Marker({
map: $scope.myMap,
position: ll
});
$scope.myMarkers = [marker, ];
}
};
$scope.showMarkerInfo = function(marker) {
$scope.myInfoWindow.open($scope.myMap, marker);
};
$scope.changeval = function(){
$scope.lat = 13.0810 ;
$scope.long = 80.2740 ;
};
}
You need to watch for changes in the scope in order to refresh the map.
Demo Plunkr
(just use the input fields above the map to change the center of the map in real time)
The important part is $scope.$watch:
var updateCenter = function() {
var ll = new google.maps.LatLng($scope.lat, $scope.long);
$scope.myMap.panTo(ll);
// eventually more stuff
}
$scope.$watch('lat', updateCenter);
$scope.$watch('long', updateCenter);
I'm rattling my brains here and cannot figure out why this is not working
var lat = Math.round(top_location.geometry.location.lat() * 1000000)/1000000;
var lng = Math.round(top_location.geometry.location.lng() * 1000000)/1000000;
geocode_results[i]['lat'] = lat;
geocode_results[i]['lng'] = lng;
geocode_results[i]['l_type'] = top_location.geometry.location_type;
marker = new google.maps.Marker({
icon: mapIcon,
position: new google.maps.LatLng(lat,lng),
map: map
});
markersArray.push(top_location.address_components[0].long_name);
Using the above created my marker(s) and plots them on my map.
Using the following code to remove the markers from the map
$scope.removemarkers = function() {
console.log($scope);
console.log(markersArray);
if (markersArray && markersArray.length) {
for (var i = 0; i < markersArray.length; i++) {
markersArray[i].setMap(null);
}
markersArray = [];
}
};
I get the following error in console.log()
TypeError: Object AB42 2DL has no method 'setMap'at
Object.$scope.removemarkers
AB42 2DL being a random postcode used when plotting a marker
markersArray doesn't contain markers, it contains strings.
Try this:
markersArray.push(marker);
I'm new with Openlayers, so not sure what is wrong. I can add markers when I change a select drop down and when I click the map. The issue comes when I zoom the map, the markers disappear.
I realised that markers don't disappear, they just move to another place, to the point 0,0.
This is the code
(function($) {
$().ready(function() {
var ZOOM_LEVEL_PROVINCE = 12;
var projection = new OpenLayers.Projection("EPSG:4326");
var map;
var markerLayer;
var initMap = function() {
map = new OpenLayers.Map ("map", {
controls:[
new OpenLayers.Control.Navigation(),
new OpenLayers.Control.PanZoomBar(),
new OpenLayers.Control.Permalink(),
new OpenLayers.Control.ScaleLine({geodesic: true}),
new OpenLayers.Control.Permalink('permalink'),
new OpenLayers.Control.MousePosition(),
new OpenLayers.Control.Attribution()],
//maxExtent: new OpenLayers.Bounds(-20037508.34,-20037508.34,20037508.34,20037508.34),
maxResolution: 156543.0339,
numZoomLevels: 19,
units: 'm',
projection: new OpenLayers.Projection("EPSG:4326"),
displayProjection: new OpenLayers.Projection("EPSG:4326")
} );
layer = new OpenLayers.Layer.OSM("Simple OSM Map");
map.addLayer(layer);
var point = getLonLatProvince('san-jose');
map.setCenter(point.transform(projection, map.getProjectionObject()), ZOOM_LEVEL_PROVINCE);
}
var initMakerLayer = function(){
markerLayer = new OpenLayers.Layer.Markers( "MarkerLayer" );
markerLayer.id = "MarkerLayer";
map.addLayer(markerLayer);
}
var showMarker = function( province ){
var point = getLonLatProvince(province);
var location = point.transform(projection, map.getProjectionObject());
showMarkerPosition(location);
}
var showMarkerPosition = function( location ){
markerLayer.clearMarkers();
var size = new OpenLayers.Size(21,25);
var offset = new OpenLayers.Pixel(-(size.w/2), -size.h);
var icon = new OpenLayers.Icon('http://www.openlayers.org/dev/img/marker.png',size,offset);
markerLayer.addMarker(new OpenLayers.Marker(location,icon.clone()));
var newPoint = location.transform(new OpenLayers.Projection("EPSG:900913"), new OpenLayers.Projection("EPSG:4326"));
$("#edit-plonlat").val( newPoint );
}
var getLonLatProvince = function( province ){
...
}
initMap();
initMakerLayer();
showMarker('san-jose');
map.events.register("click", map, function(e) {
var location = map.getLonLatFromPixel(e.xy);
showMarkerPosition(location);
});
$('#edit-pprovinces').change(function() {
var selectedPronvince = $(this).val();
var point = getLonLatProvince(selectedPronvince);
showMarker(selectedPronvince);
map.setCenter(point.transform(projection, map.getProjectionObject()), ZOOM_LEVEL_PROVINCE);
});
});
})(jQuery);
I think your call to map.getLonLatFromPixel(e.xh) is getting a location in WGS84 (EPSG:4326) since that is the projection of the map. Then you call showMarkerPosition in your "click" handler. In showMarkerPosition you transform that location from the Google to WGS84 projection, which would change a large lat/lon in meters to a much smaller lat/lon in degrees.
If you've started out with degrees for that meters-to-degrees transform, then I think you'll end up with a lat/lon that's very close to 0,0 off the West coast of Africa.
A projection transform issue is where I always start looking when I see 0,0 lat/lon's.
Although I got this working in Gmapv2..version three is proving to be a little trickier.
I wanted to add the other attributes into the infobubble from the XML file, but whereever I try and add them, it breaks the on-click marker?
<script type="text/javascript">
var infowindow;
var map;
function initialize() {
var myLatlng = new google.maps.LatLng(54.046575, -2.8007399);
var myOptions = {
zoom: 13,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
downloadUrl("http://www.xxxxxx.com/xxxxx.com/server/venue_output.php", function(data) {
var markers = data.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var latlng = new google.maps.LatLng(parseFloat(markers[i].getAttribute("latitude")),
parseFloat(markers[i].getAttribute("longitude")));
var event_name = markers[i].getAttribute("event_title");
var event_start = markers[i].getAttribute("event_start");
var event_link = markers[i].getAttribute("event_link");
var marker = createMarker(markers[i].getAttribute("event_name"),latlng);
}
});
}
function createMarker(name, latlng) {
var marker = new google.maps.Marker({position: latlng, map: map, bounce:true, icon : new google.maps.MarkerImage('http://www.gigizmo.com/gigizmo.com/app/images/marker.png')});
google.maps.event.addListener(marker, "click", function() {
if (infowindow) infowindow.close();
infowindow = new google.maps.InfoWindow({content: "<b>" + name + "</b>" });
infowindow.open(map, marker);
});
return marker;
}
</script>
How do I add my javascript values such as event_link to this marker window?
infowindow = new google.maps.InfoWindow({content: "<b>" + name + "</b>" });
You may try this code snippet, provided at : this example
function createMarker(..){
eval(" infowindow"+time+" = new google.maps.InfoWindow({ content: pt.latLng.toString() });");
eval(" marker"+time+" = new google.maps.Marker({ position: pt.latLng, map: map });");
eval(" google.maps.event.addListener(marker"+time+", \"click\", function() { infowindow"+time+".open(map, marker"+time+"); });");
time++;
//rest of your code
}
And also, speaking of my previous experiences:
be sure that your XML file does not include linebreaks.
Especially as the value you set to "name" variable.