OpenLayers Map markers disappear when map is centered on them - javascript

I'm having issues with the OpenLayers map markers. I have searched through the other answers here and on other sites but non of them really addressed the issue I'm having (at least I don't think they did. I'm fairly new to OpenLayers and Javascript, my apologies if I am wrong).
The markers appear when I load the map and page, and no errors display in the console. When I pan to the markers, as they cross into the middle third of the map at max extent, they disappear! When I zoom in, they disappear before I can even get them on screen (never errors from the console). Here is my javascript code for generating the map and markers. Thank you in advance for all of your help.
Additional notes: When I use static numbers (and not values retrieved from my XML file) for marker positioning, the markers do not disappear on pan or zoom. I am so confused.
RESOLVED: I used a different XML file and the markers stopped disappearing for some reason, I have no idea why.
Code:
$(function()
{
var map = new OpenLayers.Map("rcp1_map");
layer = new OpenLayers.Layer.OSM("OpenStreetMap");
map.addLayer(layer);
map.addControl(new OpenLayers.Control.LayerSwitcher());
map.setCenter(new OpenLayers.LonLat(0, 0), 3);
var markers = new OpenLayers.Layer.Markers("Markers");
map.addLayer(markers);
//load and retrieve values from XML file here
var xmlDoc=loadXMLDoc("http://whxlab3.dart.ns.ec.gc.ca/~brinka/
EMETsiteV1/EMETsite.xml");
var z=xmlDoc.getElementsByTagName("buoy_number");
var y=xmlDoc.getElementsByTagName("lat");
var x=xmlDoc.getElementsByTagName("long");
//create and add all map markers here
for(i=0; i<x.length; i++)
{
//use loaded XML file to retrieve values for marker positions
var px = x[i].childNodes[0].nodeValue;
var py = y[i].childNodes[0].nodeValue;
var pz = z[i].childNodes[0].nodeValue;
console.log("Testing Console", px, py);
var size = new OpenLayers.Size(32, 37);
var offset = new OpenLayers.Pixel(-(size.w/2), -size.h);
var icon = new OpenLayers.Icon('stock_images/buoy_arrow.png', size,
offset);
icon.setOpacity(0.7);
var lonlat = new OpenLayers.LonLat(px, py);
lonlat.transform(new OpenLayers.Projection("EPSG:4326"),
new OpenLayers.Projection("EPSG:900913"));
var marker = new OpenLayers.Marker(lonlat, icon);
marker.events.register("mouseover", marker, function(){
console.log("Over the marker "+this.id+" at place
"+this.lonlat);
this.inflate(1.2);
this.setOpacity(1);
});
marker.events.register("mouseout", marker, function(){
console.log("Out the marker "+this.id+" at place
"+this.lonlat);
this.inflate(1/1.2);
this.setOpacity(0.7);
});
marker.events.register("click", marker, function(){
console.log("Clicked "+this.id+" at place "+this.lonlat);
popup = new OpenLayers.Popup.FramedCloud("chicken",
marker.lonlat, new OpenLayers.Size(200, 200),
("Buoy Number: "+pz), null, true);
map.addPopup(popup);
});
markers.addMarker(marker);
}
//:*** To here
});

Related

Google Map not showing smooth lines between map grid squares

I have a question that may be somewhat strange. I have implemented Google Maps on different parts of my website, but in one part the map canvas is not showing smooth imaging. It is showing the distinctive grid squares. I have double checked the map api reference and it seems to be the right code. I have also checked against other parts of my site and the code is almost identical.
Here is the code I have for the offending grid lines map (googlemap.js)
var scriptTag = '<' + 'script src="http://maps.google.com/maps/api/js?v=3&key={my-key}&sensor=false">'+'<'+'/script>';
document.write(scriptTag);
var latlng = '0';
var imagename = '';
var GPSLatitude = '48.2099177267394';
var GPSLongitude = '16.37563705444336';
window.setTimeout('initGmaps();',1000);
function initGmaps()
{
var myOptions = {
zoom:4,
center:new google.maps.LatLng(GPSLatitude,GPSLongitude),
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
marker = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(GPSLatitude,GPSLongitude)
});
function placeMarker(location)
{
if (marker)
{
marker.setPosition(location);
}
else
{
marker = new google.maps.Marker({
position: location,
map: map
});
}
}
// google.maps.event.addDomListener(window, 'load', initialize); <-- if I leave this in, it doesn't load the map for some strange reason
Here is where I call the map (functions.php <-- this sends the co-ords to the map)
$google_map = "
<script type='text/javascript' src='googlemap.js'></script>
<script type='text/javascript'>
GPSLatitude = '$GPSLatitude';
GPSLongitude = '$GPSLongitude';
imagename = '$image_name';
</script>
";
Here are a couple of screenshots of the issue
Distinctive Grid Lines
Smooth Image
Just not quite sure where I am going wrong with this. Any help is greatly appreciated

Google Maps centre changing issue

I'm using a combination of Google Maps, GeoXML and MarkerClusterer to map historic texts to places. The user can choose the texts they want to map, and the page goes and gets the KML for those group of texts and displays it with MarkerClusterer.
Something is causing the page to recenter over India/China when new texts are selected (bottom left corner: http://lakes.jhadley.net/lit_file.htm.
Here is the primary function that deals with the map:
function loadMap(myLat, myLong, zoomLevel, generatedUrl) {
var mapOptions = {
center: new google.maps.LatLng(myLat, myLong),
zoom: zoomLevel,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var mcOptions = {gridSize: 80, maxZoom: 15};
var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
markerclusterer = new MarkerClusterer(map, [], mcOptions);
var myParser = new geoXML3.parser({
map: map,
singleInfoWindow:true,
suppressInfoWindows:true,
createMarker:function(placemark){
var point = placemark.latlng;
var info = "<pre" + placemark.name + "<br /><br />" + placemark.description + "</pre>";
var marker = new google.maps.Marker({position:point});
//Suppress the speachbubbles and have them appear in a text window instead
google.maps.event.addListener(marker, 'click', function() {
var text = placemark.description.replace(/ target="_blank"/ig, "");
showInContentWindow(text);
}); //Add listener
markerclusterer.addMarker(marker);
}
});
myParser.parse("http://lakes.jhadley.net/generateKml/"+generatedUrl);
function showInContentWindow(text) {
var sidediv = document.getElementById('kwic_window');
sidediv.innerHTML = text;
} //showInContentWindow
} //function loadMap
I can't personally see why the map centre is being repositioned over India/China when new texts are loaded. Can anyone tell me what I'm missing?
by default geoxml3 attempts to zoom to fit the data. If you don't want it to do that, set the "zoom" option to false. From the documentation:
zoom | boolean (true) | If true, the parser will automatically move the map to a best-fit of the geodata after parsing of a KML document completes.
That is where the "center" of the markers are:
http://www.geocodezip.com/geoxml3_test/v3_geoxml3_kmltest_linktoB.html?filename=http://www.geocodezip.com/geoxml3_test/SO_20140312_1,4.kml
http://www.geocodezip.com/geoxml3_test/v3_geoxml3_kmltest_linktoB.html?filename=http://www.geocodezip.com/geoxml3_test/SO_20140312_1.kml

Add a marker on mouse click and remove the existing on in openlayers?

I am using Openlayers map. I want a feature when a user clicks on the map the marker should be created but at the same time the existing marker which is already on the map should be deleted or removed and only the latest one should be visible.
var markers = new OpenLayers.Layer.Markers( "Markers" );
markers.id = "Markers";
me.OpenLayers.addLayer(markers);
/*myMarker = new OpenLayers.Marker(new OpenLayers.Marker( 56.512438257836,27.335700987698 ));
markers.addMarker(myMarker);*/
var size = new OpenLayers.Size(30,30);
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);
//map.setCenter (lonLat, zoom);
me.OpenLayers.events.register("click", kijs_map_container, function(evt) {
var lonlat = me.OpenLayers.getLonLatFromViewPortPx(evt.xy).transform(new OpenLayers.Projection("EPSG:900913"), new OpenLayers.Projection("EPSG:4326"));
$("#edit-field-jena-seta-map-openlayers-wkt").val('GEOMETRYCOLLECTION(POINT('+lonlat.lat+' '+lonlat.lon+'))');
var pos = me.OpenLayers.getLonLatFromPixel(evt.xy);
alert(baltic_long);
var marker = new OpenLayers.Marker(new OpenLayers.LonLat(baltic_lat, baltic_long),icon);
markers.addMarker(marker);
marker.events.register("click", marker, function(e){
});
//updateMaker(myMarker, pos);
});
Remove all markers on layer before creating and adding new one:
markers.clearMarkers();
markers.addMarker(marker);
See clearMarkers for more details.
Probably when you place var marker and initialize icon outside of the me.OpenLayers.events.register(); scope it will possibly be reinitiated the moment you click again for a new marker.
var marker;
icon = new OpenLayers.Icon( ... );
me.OpenLayers.events.register("click", kijs_map_container, function(evt) {
var pos = me.OpenLayers.getLonLatFromPixel(evt.xy);
marker = new OpenLayers.Marker(pos, icon);
markers.addMarker(marker);
});
At least I haven't tested this particular example here, but was my experience with a map editor I'm making.

Plotting bus route with Google Maps

I'm working on a property rental site. On the site I'd like to have a Google map, with all of the properties marked, and the local bus routes drawn, so that renters can see the proximity of the properties to the route.
I've achieved the first part of the problem; I've plotted the properties using markers. Now I need to add the bus route.
I've looked in to this and I can't quite work out the best way to achieve it. I looked at polylines and at using this tool, but the route is complex and would take hundreds of co-ordinates.
There is some kind of route api, as in this post but apparently it can only take 8 waypoints. Is that right?
Ideally I'd like to draw the map by selecting a start point, an end point, and dragging the route into place; and then somehow importing that route into what I have.
Here is the exact route that I want to import: http://www2.warwick.ac.uk/services/accommodation/landlords/12busroutes/.
My code to plot the properties is:
var siteRoot = "<?php bloginfo('stylesheet_directory');?>/";
var markers = [
<?php
$my_query = new WP_Query( 'post_type=properties' );
while ($my_query->have_posts()) : $my_query->the_post();
kdev_maps('list');
endwhile; // end of the loop.
?>
];
function googlemap() {
jQuery('#map_canvas').css({'height': '400px'});
// Create the map
// No need to specify zoom and center as we fit the map further down.
var map = new google.maps.Map(document.getElementById("map_canvas"), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
streetViewControl: false
});
// Create the shared infowindow with two DIV placeholders
// One for a text string, the other for the StreetView panorama.
var content = document.createElement("div");
var title = document.createElement("div");
var boxText = document.createElement("div");
var myOptions = {
content: boxText
,disableAutoPan: false
,maxWidth: 0
,pixelOffset: new google.maps.Size(-117,-200)
,zIndex: null
,boxStyle: {
background: "url('"+siteRoot+"images/house-icon-flat.png') no-repeat"
,opacity: 1
,width: "240px"
,height: "190px"
}
,closeBoxMargin: "10px 0px 2px 2px"
,closeBoxURL: "http://kdev.langley.com/wp-content/themes/langley/images/close.png"
,infoBoxClearance: new google.maps.Size(1, 1)
,isHidden: false
,pane: "floatPane"
,enableEventPropagation: false
};
var infoWindow = new InfoBox(myOptions);
var MarkerImage = siteRoot+'images/house-web-marker.png';
// Create the markers
for (index in markers) addMarker(markers[index]);
function addMarker(data) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(data.lat, data.lng),
map: map,
title: data.title,
content: data.html,
icon: MarkerImage
});
google.maps.event.addListener(marker, "click", function() {
infoWindow.open(map, this);
title.innerHTML = marker.getTitle();
infoWindow.setContent(marker.content);
infoWindow.open(map, marker);
jQuery(".innerinfo").parent().css({'overflow':'hidden', 'margin-right':'10px'});
});
}
// Zoom and center the map to fit the markers
// This logic could be conbined with the marker creation.
// Just keeping it separate for code clarity.
var bounds = new google.maps.LatLngBounds();
for (index in markers) {
var data = markers[index];
bounds.extend(new google.maps.LatLng(data.lat, data.lng));
}
map.fitBounds(bounds);
var origcent = new google.maps.LatLng(map.getCenter());
// Handle the DOM ready event to create the StreetView panorama
// as it can only be created once the DIV inside the infowindow is loaded in the DOM.
closeInfoWindow = function() {
infoWindow.close();
};
google.maps.event.addListener(map, 'click', closeInfoWindow);
google.maps.event.addListener(infoWindow, 'closeclick', function()
{
centermap();
});
function centermap()
{
map.setCenter(map.fitBounds(bounds));
}
}
jQuery(window).resize(function() {
googlemap();
});
Any help is much appreciated.
Its worth looking at two things:
1) The GTFS format (https://developers.google.com/transit/gtfs/reference) this is a csv-based format that allows someone to cross reference transit times and routes, if you are lucky then the data will have been assembled for you for your transit authority :)
2) If you can pull in the coordinates then you can make a line feature as long as you want (within the bounds of browser capacity). This is done in much the same way as you pull in markers, except you pull the features you want into a polyline:
like this (from gmaps docs):
var flightPlanCoordinates = [
new google.maps.LatLng(37.772323, -122.214897),
new google.maps.LatLng(21.291982, -157.821856),
new google.maps.LatLng(-18.142599, 178.431),
new google.maps.LatLng(-27.46758, 153.027892)
];
var flightPath = new google.maps.Polyline({
path: flightPlanCoordinates,
strokeColor: "#FF0000",
strokeOpacity: 1.0,
strokeWeight: 2
});
you will build your array from php, of course :)
hope that helps.
If you use free google maps you can use a start point, end point and 8 way point. In google maps api premiere you can use 23 way point for routing vehicles

Google Maps Api: How to add a marker and speech bubble?

I have managed to get a google map on my site using Javascript api of google maps.. and it works great...
Can anyone tell me how i can add the Speech bubble and marker ... Pictured here... http://code.google.com/apis/maps/
Basically my site displays a simple map but its missing the marker for where office is and a speech bubble where i want to place the office address
Any help would be really appreciated.
Here is the code i have so far
if (GBrowserIsCompatible()) {
var map = new GMap2(document.getElementById("map"));
map.setCenter(new GLatLng(40.466997, -3.705482), 13);
}
A marker can be added using the GMarker class ; for instance, to add a point to a map, I would use something like this :
var point = new GPoint(45.779915302498935, 4.803814888000488);
var marker = new GMarker(point);
map.addOverlay(marker);
(Of course, you'll have to adapt the coordinates to the ones of your office, so it doesn't point to some point in France ^^ ; I suppose the ones you posted should do the trick ;-) )
And for an Information window, you can use the GMarker.openInfoWindowHhtml method, on your marker.
I guess something like this should do the trick :
if (GBrowserIsCompatible()) {
var map = new GMap2(document.getElementById("map"));
map.setCenter(new GLatLng(40.466997, -3.705482), 13);
var point = new GPoint(-3.705482, 40.466997);
var marker = new GMarker(point); // Create the marker
map.addOverlay(marker); // And add it to the map
// And open some infowindow, with some HTML text in it
marker.openInfoWindowHtml(
'Hello, <strong>World!</strong>'
);
}
And the result looks like this :
(source: pascal-martin.fr)
Now, up to you to build from here ;-)
Here is some code that shows how to use an XML file to load multiple markers. Also this site is the best there is for Google Maps examples and tutorials
// A function to create the marker and set up the event window
function createMarker(point,name,html) {
var marker = new GMarker(point);
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml(html);
});
// save the info we need to use later for the side_bar
//gmarkers.push(marker);
// add a line to the side_bar html
//side_bar_html += '<a href="javascript:myclick(' + (gmarkers.length-1) + ')">' + name + '<\/a><br>';
return marker;
}
// This function picks up the click and opens the corresponding info window
function myclick(i) {
GEvent.trigger(gmarkers[i], "click");
}
$(document).ready(function(){
// When class .map-overlay-right is clicked map is loaded
$(".map-overlay-right").click(function () {
var map = new GMap2(document.getElementById('map-holder'));
$("#map-holder").fadeOut('slow', function(){
var gmarkers = [];
map.addControl(new GSmallMapControl());
map.addControl(new GMapTypeControl());
// Get XML file that contains multiple markers
$.get("http://www.foo.com/xml-feed-google-maps",{},function(xml) {
$('marker',xml).each(function(i) {
// Parse the XML Markers
html = $(this).text();
lat = $(this).attr("lat");
lng = $(this).attr("lng");
label = $(this).attr("label");
var point = new GLatLng(lat,lng);
var marker = createMarker(point,label,html);
map.addOverlay(marker);
});
});
});
$("#map-holder").fadeIn('slow');
var Asia = new GLatLng(19.394068, 90.000000);
map.setCenter(Asia, 4);
});
});

Categories