Inserting HTML DOM elements loaded from an XML file w/ jQuery - javascript

If there's an easier/better way to do this, please say so (I'm just starting to learn JS, first language), but here's what I am trying to accomplish:
I have an XML file containing a set of markers for google maps, ie:
<?xml version="1.0" encoding="UTF-8"?>
<markers>
<marker name="Our Venue" lat="32.735873" lng="-117.255323" icon="wedding">
<div id="info"> <h2>Title</h2> <a href="http://site.com/link.html">Official web site</a> <p>Blah blah blah!</p> </div>
</marker>
...
I can get jQuery to load all the info and parse it into google.maps.Marker(s):
jQuery.get("map_data.xml", {}, function(data) {
jQuery(data).find("marker").each(function() {
var marker = jQuery(this);
var latlng = new google.maps.LatLng(parseFloat(marker.attr("lat")), parseFloat(marker.attr("lng")));
var title = marker.attr("name");
var icon = marker.attr("icon");
var markerContent = marker.contents();
var marker = new google.maps.Marker({
position: latlng,
map: map,
icon: crIconRegistry[icon],
title: title
});
Now, I'd like when I click on the map marker for it to insert the HTML content from the XML file into a DIV on the page, something like this:
jQuery.jcps.insertFromMap = function (speed, target, markerContent) {
if (speed == 0) {
$(target).html(markerContent);
}
else {
$(target).fadeToggle(speed, function(){$(this).html(markerContent);}).fadeToggle(speed);
}
}
google.maps.event.addListener(marker, "click", function() {
jQuery.jcps.insertFromMap(crFaderSpeed, crDefaultPanel, markerContent);
});
However, when I try this (in safari, haven't tested others yet) I get the following error: "WRONG_DOCUMENT_ERR: DOM Exception 4: A Node was used in a different document than the one that created it"
TIA for any help!

Could it be that you use markerContent more than once? It may lead to wonderous things: example. A way around that is to use .clone: example

For full details, please see the excellent explanation at Cross-Browser Scripting with importNode()
You have to check if importNode is supported before adding markerContent in target.
If you are using jQuery 1.5 then see parseXML(), which seems to have taken care of this issue (though I haven't tested it myself).

Solved, although I'm not sure why this made a difference. My previous code used the variable name "marker" twice: first to hold the XML jQuery object, then re-defined to hold the google.maps.Marker object. There must have been a conflict I was unaware of, because changing the variable name solved the issue. Revised code:
jQuery.get("map_data.xml", {}, function(data) {
jQuery(data).find("marker").each(function() {
var node = jQuery(this);
var latlng = new google.maps.LatLng(parseFloat(node.attr("lat")), parseFloat(node.attr("lng")));
var title = node.attr("name");
var icon = node.attr("icon");
var markerContent = node.contents().text();
var marker = new google.maps.Marker({
position: latlng,
map: map,
icon: crIconRegistry[icon],
title: title
});
google.maps.event.addListener(marker, "click", function() {
jQuery.jcps.insertFromMap(crFaderSpeed, crDefaultPanel, markerContent);
});
});
});
Thanks though for the assistance!

your original code failed because you tried to merge dom nodes from one document into another - safari balks on that (firefox 7, chrome 15 don't though they probably should). as ritesh pointed out, you can call the dom function importNode.
however, to avoid a deep copy of the dom node to be imported, use adoptNode.
it is supported by all major browsers including ie 9 (personally tested on safari 5, chrome 15, firefox 7).
hopefully this is helpful additional info,
best regards, carsten

Related

Error MapSVG.Location is not a constructor

I am using the MapSVG plug in in WP and from the JS panel of the plug in I am trying to insert a marker, as per the documentation. But it gives me the error:
MapSVG.Location is not a constructor.
How can I solve this?
The code I use is as follows:
var location = new MapSVG.Location({
lat: 55.22,
lng: 64.12,
img: "/path/to/image.png"
});
var marker = new MapSVG.Marker({
location: location,
mapsvg: mapsvgInstance
});
// The marker is created but still not added to the map. Let's add it:
mapsvg.markerAdd(marker);
Taken from the official documentation at this link: https://mapsvg.com/docs/api/#mapsvgmarker
I've tried to do some research but can't figure out how I can solve the problem. Can you help me?
Currently the problem keeps recurring. The plug-in version is: 6.2.25 and the wp version is: 6.0.2

Google map API in my html website

hello I have a problem I wish to integrate ue google map in my site but I do not understand it appears when I update the page but then it disappears. In the console it says "no APIkey" but I did it several times. I followed the site: developers.google
but I do not understand where the error lies. I put the html part if a person understand the error please ! I also follow this topic google api in my website but nothing appears !
<div id="map"></div>
<script>
function initMap() {
var ff = {
lat: 50.638181,
lng: 3.058227
};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 17,
center: ff
});
var marker = new google.maps.Marker({
position: ff,
map: map
});
}
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDWdGA-ndsHMtR5-cdZrc5SHtfKKBG5Bfg&callback=initMap">
</script>
Console says:-
https://developers.google.com/maps/documentation/javascript/error-messages#api-not-activated-map-error
so activate your google map API key under project.
Your API key is not activated. Make sure to generate a new one following the guide: https://developers.google.com/maps/documentation/javascript/get-api-key?hl=de

marker symbols for leaflet_Ajax, looking always for default marker in js/images/marker-icon.png

I am new to leaflet but have developed some interactive maps in the past. I started working on displaying a gps device on a UAV. The UAV sends the location information on a server and has a php code that returns some sensor values upon relevant request (in geojson format, so I dont have to do much... phew). I was looking for some solutions for how to do it seamlessly using Ajax when i came across leaflet_Ajax.. I had a lot of issues which were mostly resolved by some questions on stackoverflow for example this one and a few others.
Now here is how i am writing my code for the markers for the points:
var geojsonLayer = new L.GeoJSON.AJAX("myserver/get_geoj.php?stype=particle&sval[min]=2&sval[max]=26",{pointToLayer: redmarkers, onEachFeature: popUp});
function popUp(feature, layer) {
layer.bindPopup(feature.properties.sensor_v);
},
I have another function redmarkers that returns red colored circle markers. What happens is that finally it is loading the data from the server... phewh.... but it does not bind the popup or the markers to this layer. It looks for the (I guess some) default marker images in the js/images/marker-icon.png as marker symbol. This doesnot exist and so it gives me an error. But if i take any random image and call it marker-icon.png and put it in the desired location it shows that image on the map but still does not bind the popup.
What am i doing wrong. As i am new to stack overflow as well if you need more information or if i am not asking the question right please let me know.
Okay So I resolved it, but thought that somebody else might do similar mistakes later and I should answer this question.
I had accidentally edited my leaflet.js file somehow. I dont remember doing that though. I deleted the dummy image that I had put in the js/images folder for marker-icon.png and it was still showing the same marker. The i realized it had cached it so i disabled chache, only to realize in the console that the error had something to do with leaflet.js. I updated the version of leaflet.js (had a backup copy on my disk, so the same version didnt update or something), and it works fine now. Here is my current code
var geojsonLayer = new L.GeoJSON.AJAX(dataurl,{
pointToLayer: function (feature, latlng) {
return L.circleMarker(latlng, redRegionStyle);
},
onEachFeature: onfeature
});
function onfeature(feature, layer)
{
layer.on(
{
mouseover: highlightFeature,
mouseout: resetHighlight
});
layer.bindPopup(feature.properties.sensor_v.toString());
}
It works perfectly highlights the features as i like and also has the popup bind to the features.
Sorry to all those who i bothered by asking this question as it was my own sily mistake

Geolocation Error Detection

I'm using Geolocation but I'm having trouble recognizing errors to be able to offer an alternative.
My HTML looks like this:
<button onclick="getLocation()">Get your location now</button>
<div id="google_canvas"></div>
<p id = 'error'></p>
My script looks like this:
function getLocation(){
if(navigator.geolocation)
{
var map;
var mapOptions =
{
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById('google_canvas'), mapOptions);
navigator.geolocation.getCurrentPosition(function(position)
{
var geolocate = new google.maps.LatLng(position.coords.latitude, position.coords.longitude),latitude=document.getElementById("latitude"),longitude=document.getElementById("longitude");
var infowindow = new google.maps.InfoWindow(
{
map: map,
position: geolocate,
content:
' * output content within map * '
});
map.setCenter(geolocate);
latitude.value = position.coords.latitude;
longitude.value = position.coords.longitude;
});
}
else
{
document.getElementById('error').innerHTML = 'No Geolocation Support';
}
};
google.maps.event.addListener(map, 'idle', function() {
});
My version of IE9 does not support Geolocation (I've tried their test site with their own script), but it gives me no error or warning, plus if I do not allow location in Firefox or Chrome, I don't get any error or alert either.
Can someone help? If it cannot run, i can offer an alternative so I don't think i need to look through error codes so much, but I do need to be able to detect failure so I can offer my alternative, but the error portion in my script will not run, regardless.
My question really is, why won't this else run?
else
{
document.getElementById('error').innerHTML = 'No Geolocation Support';
}
Thanks
For your error message it will appear if your browser does not support geolocation, to enable disable geolocation on browser that supports it you usually need to take look next to the address bar there should be a small icon that you can use to disable/enable geolocation.
In order for you to detect previous decision weather you enabled/disabled geolocation you can use the solution I suggested in this article :
Is there a way of detecting whether a user has already given permission to use navigator.geolocation?
For IE9 it is working fine, the only thing is you should click Allow blocked cnotent at the bottom of the web page.

LEAFLET: Custom images in the Layer Control Tutorial?

I have followed the leaflet tutorial on how to create Layer Control and the custom markers:
Markers:http://leafletjs.com/examples/custom-icons.html
Control: http://leafletjs.com/examples/layers-control.html
I am using the control code and i would like to add my custom marker to this. When applying the code it the map goes blank and breaks. Im not sure if it's something do to with the positioning with the "add to map" and "bindpopup". Any help would be great.
CODE:
[CLOUDMADE API KEY AND INFO HERE]
var officeIcon = L.icon({
iconUrl: 'images/office1.png'
});
var london = L.marker([51.3512542357518,-0.461769104003906],{icon: officeIcon}).addTo(map).bindPopup('<b>Office Address</b>');
var cities = L.layerGroup([london]);
var minimal = L.tileLayer(cloudmadeUrl, {styleId: 22677}),
midnight = L.tileLayer(cloudmadeUrl, {styleId: 999}),
motorways = L.tileLayer(cloudmadeUrl, {styleId: 46561});
var map = L.map('map', {
center: new L.LatLng(54.980000,-1.5975022315979004),
zoom: 10,
layers: [minimal, motorways, cities]
});
var baseMaps = {
"Minimal": minimal,
"Night View": midnight,
};
var overlayMaps = {
"Motorways": motorways,
"Display Markers": cities
};
map.addControl(new MyControl());
L.control.layers(baseMaps, overlayMaps).addTo(map);
The problem is that you're adding the marker to the map before you have defined the map. I would recommend using firebug for firefox or the equivalent in chrome. That way you could look at the console and you would see the error:
'Uncaught TypeError: Cannot call method 'addLayer' of undefined'
L.Marker.L.Class.extend.addTo leaflet-src.js:2993
addVehicleContentUI obelix.dev:1074
(anonymous function) obelix.dev:718
(anonymous function) obelix.dev:1292
p.event.dispatch jquery-1.8.0.min.js:2
g.handle.h
This pointed me to the L.Marker which made me realise that you hadn't defined the map yet. The problem you have is that you're adding the marker to the map as well as adding it to the group layer. Just don't add it to the map (as per the tutorial you were following). so remove the code:
.addTo(map)
from:
var london = L.marker([51.3512542357518,-0.461769104003906],{icon: officeIcon}).addTo(map).bindPopup('<b>Office Address</b>');
The next problem is that MyControl isn't a control, I commented out the following line:
map.addControl(new MyControl());
From your code snippet, I presume you have a key from cloudmade. If so then it should work fine. I tested it locally and everything was good.
I do highly recommend getting firebug if you're using firefox or the equiv for chrome if you use chrome. Looking at the console will show you these problems and you can even set breakpoints and step through the javascript as it executes. An invaluable tool for javascript programming IMHO.
Cheers.

Categories

Resources