I'm trying to load a google map within a jquery ui accordion with contents loaded by ajax.
$("h2", "#accordion").click(function(e) {
var contentDiv = $(this).next("div");
if (contentDiv.children().length == 1)
{
contentDiv.load($(this).find("a").attr("href"));
contentDiv.ready(function(){
var latlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
})
}
});
That's my current code (Google Maps API V3), but it redirects to the url of the href when I click currently, obviously with no google map because there's no javascript in this response. If I comment out the map line everything works fine (except the map itself).
Well, the thread is dead but since I lost some hours on similar problem I feel like sharing my solution.
I have a jqueryui accordeon with a googlemap in each pane.
The problem is accordeon have no size for hidden panes, and googlemaps uses that size to render the maps.
So I save every 'map' and 'marker' (gmaps terminology) in an indexed array (var maps) and when user changes accordeon pane, I 'refresh' the corresponding gmap.
The catch there is that event resize is not enough, you have to force zoom for redrawn and even then because of the size it had on a closed pane, your marker for that map is completelly off screen so you have recenter it based on the marker position.
$(document).ready(function(){
if($('div.map_canvas').length>0) initializeMap(); //init map
if($('#accordion').length>0) $("#accordion .items").accordion(); //init accordeon
$("#accordion .items").bind("accordionchange", function(event, Element) {
current=maps[Element.options.active];
google.maps.event.trigger(current.map, 'resize'); //resize
current.map.setZoom( current.map.getZoom() ); //force redrawn
current.map.setCenter(current.marker.getPosition()); //recenter on marker
})
});
var maps=Array();
function initializeMap() {
var geocoder;
$('div.map_canvas').each(function(index,Element) {
var address = $(Element).text();
var myOptions = {
zoom: 15,
navigationControl: true,
navigationControlOptions: { style: google.maps.NavigationControlStyle.SMALL },
mapTypeControl: true,
mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
scaleControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
geocoder = new google.maps.Geocoder();
geocoder.geocode({'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
myOptions.center = results[0].geometry.location;
map = new google.maps.Map(Element, myOptions);
marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
});
maps.push({marker:marker,map:map}); //save those
} else {
alert('The address could not be found for the following reason: ' + status);
}
});
})
}
It didn't occur to me until now, but since the content of each accordion is dynamically loaded, this constitutes an illegal cross site request. The map must be obtained from my own web server and transmitted to the ajax request in the accordion or the google map must be loaded once and manipulated into the dom of the accordion panes being loaded.
Related
I have a questions, currently I have in a webpage some markers that I get from a xml file using position of latitude and longitude.
So I would like to know how to enable to option of the marker listener to activate or show the option to send the user using the cellphone directions (gps). Like in android it I click on the marker it shows the option to activate gps directions, but on web I don't know how.
So for each direction if is clicked send the current position to the gps directions app of the cellphone.
Currlently I have this code:
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 12
});
var infoWindow = new google.maps.InfoWindow({map: map});
// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
infoWindow.setPosition(pos);
infoWindow.setContent('Location found.');
map.setCenter(pos);
}, function() {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
}
// Change this depending on the name of your PHP or XML file
downloadUrl('https://www.mysite/dataMaps.php', function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName('marker');
Array.prototype.forEach.call(markers, function(markerElem) {
var name = markerElem.getAttribute('name');
var address = markerElem.getAttribute('address');
var type = markerElem.getAttribute('type');
var point = new google.maps.LatLng(
parseFloat(markerElem.getAttribute('lat')),
parseFloat(markerElem.getAttribute('lng')));
var infowincontent = document.createElement('div');
var strong = document.createElement('strong');
strong.textContent = name
infowincontent.appendChild(strong);
infowincontent.appendChild(document.createElement('br'));
var text = document.createElement('text');
text.textContent = address
infowincontent.appendChild(text);
var icon = customLabel[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
label: icon.label
});
marker.addListener('click', function() {
infoWindow.setContent(infowincontent);
infoWindow.open(map, marker);
//map.setCenter(marker.getPosition());
});
});
});
}
And
I foun this in google site:
function displayRoute(origin, destination, service, display) {
service.route({
origin: origin,
destination: destination,
waypoints: [{location: 'Adelaide, SA'}, {location: 'Broken Hill, NSW'}],
travelMode: 'DRIVING',
avoidTolls: true
}, function(response, status) {
if (status === 'OK') {
display.setDirections(response);
} else {
alert('Could not display directions due to: ' + status);
}
});
}
But in waypoints: not sure how to send the latitude and longitude parameters and if it will work on mobile devices to trigger the gps directions app :S
Any suggestions?
Finally I saw how, in the infowindow you just need to add this:
nav
I found it here: Is there a way to invoke navigation from mobile browser?
I'm trying to add a clickable route on Geocoder example from Appcelerator. The problem is that I'm not getting any event when clicking at the route object.
Here's my code:
var cord1= {
latitude:29.078685,
longitude:-110.971205,
};
var cord2= {
latitude:29.081496,
longitude:-110.959232,
};
var route1 = [cord1, cord2];
var route = MapModule.createRoute({
points : route1,
color : "red",
width : 5.0
});
route.addEventListener('click', function(e){
Ti.APP.info(e);
});
$.mapview.addRoute(route);
The Modules.Map.Route object doesn't have any events. None of the map objects do, except the map view itself, and we can use the mapview's click event to listen for clicks, and then check the clicksource property to see what was clicked on the map.
The catch is that routes won't generate a click event, but polylines do, so the workaround is to use a polyline and look for the clicksource in the mapview's click event. Something like this should work:
var coord1 = [-110.971205, 29.078685];
var coord2 = [-110.959232, 29.081496];
var route1 = [coord1, coord2];
var route = MapModule.createPolyline({
points: route1,
strokeColor: "#ff0000",
strokeWidth: 5
});
$.mapview.addPolyline(route);
$.mapview.addEventListener('click', function (e) {
//check the clicksource for 'polyline'
console.log(e.clicksource);
});
Good afternoon,
I have a div over the ol3 map with one list of marker. When the user clic on a marker, the center's map is updated with the coordinate of this marker.
I tried that the user have the possibility to zoom on the map when he "pinch" on the layer on top.
I successed to intercept the event on the "layerOnTop" and replicate it to the map layer. With console.log, I saw that the job is correctly done but there is any reaction on the map.
You can see the code : http://jsfiddle.net/2ek4j3a4/
var center = ol.proj.transform([4.90756, 45.5172], 'EPSG:4326', 'EPSG:3857');
var map = new ol.Map({
layers: [new ol.layer.Tile({source: new ol.source.OSM()})],
target: 'map',
controls: ol.control.defaults({attributionOptions: ({ collapsible: false})}),
view: new ol.View({center: center,zoom: 12})
});
$('#layerOnTop').on("touchmove", function(event) {
var scale = event.originalEvent.touches;
if (scale.length==2) {
event.preventDefault();
var bottomEvent = new $.Event("touchmove");
bottomEvent.pageX = event.pageX;
bottomEvent.pageY = event.pageY;
$("#map").trigger(bottomEvent);
}
});
$('#map').on("touchmove", function(event) {console.log('ok')})
I did my test with an Android phone.
Somebody have an idea, please ?
I finally found :) There was 2 errors in my code :
1) target should be the canvas element in div#map and not #map himself
2) I fixed the touch identifier by Date.now() and add +1 for the second, it was certainely too big
See below the code if one day somebody search ...
$('#layerOnTop').on("touchstart touchmove touchend", function(event) {
view = document.getElementById('map').ownerDocument.defaultView;
if (event.originalEvent.touches.length==2) {
var target = document.getElementById('map').getElementsByTagName('canvas')[0];
var pageX1 = event.originalEvent.touches[0].pageX;
var pageY1 = event.originalEvent.touches[0].pageY;
var pageX2 = event.originalEvent.touches[1].pageX;
var pageY2 = event.originalEvent.touches[1].pageY;
var touch1 = document.createTouch(view, target, 0, pageX1, pageY1, 0, 0);
var touch2 = document.createTouch(view, target, 1, pageX2, pageY2, 0, 0);
var touchList = document.createTouchList(touch1, touch2);
var touchEvent = new TouchEvent(event.type, {cancelable: true, bubbles: true, touches: touchList, targetTouches: touchList, changedTouches: touchList})
target.dispatchEvent(touchEvent);
}
});
http://jsfiddle.net/2ek4j3a4/7/
I'm simply trying to replace the lat long coords to use the browsers geolocation yet I'm getting no result...
Code for the geolocation is;
<script> var coords = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
function initAutocomplete() {
var map = new google.maps.Map(document.getElementById('map'), {
center: coords,
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
The rest of the code points to the simple places api service;
// Create the search box and link it to the UI element.
var input = document.getElementById('pac-input');
var searchBox = new google.maps.places.SearchBox(input);
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
// Bias the SearchBox results towards current map's viewport.
map.addListener('bounds_changed', function() {
searchBox.setBounds(map.getBounds());
});
var markers = [];
// Listen for the event fired when the user selects a prediction and retrieve
// more details for that place.
searchBox.addListener('places_changed', function() {
var places = searchBox.getPlaces();
if (places.length == 0) {
return;
}
// Clear out the old markers.
markers.forEach(function(marker) {
marker.setMap(null);
});
markers = [];
// Create a marker for each place.
markers.push(new google.maps.Marker({
map: map,
icon: icon,
title: place.name,
position: place.geometry.location
}));
if (place.geometry.viewport) {
// Only geocodes have viewport.
bounds.union(place.geometry.viewport);
} else {
bounds.extend(place.geometry.location);
}
});
map.fitBounds(bounds);
});
}
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(success);
} else {
error('Geo Location is not supported');
}
</script>
I cannot for the life of me find any reliable tutorials on-line...
I have a map that has lots of markers pulled from a database. Each one displays an InfoWindow with a placename and the lat and lng of the location. I need to have the placename affiliated with a marker added to and HTML textbox on click. I can't seem to find any tutorials on this. Maybe someone can point me in the right direction. I am trying to learn this on my own so apologies if it is sloppily designed. Thanks for your help in advance.
function load() {
var map = new google.maps.Map(document.getElementById("map_canvas"), {
center: new google.maps.LatLng(41.640078, -102.669433),
zoom: 3,
mapTypeId: 'roadmap'
});
var infoWindow = new google.maps.InfoWindow;
downloadUrl("mymap.php", function(data) {
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");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var html = "<b>" + name + "</b> <br/>" + point;
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);
}
});
}
function bindInfoWindow(marker, map, infoWindow, html) {
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
}
It needs to go into a simple textbox like this:
<input type = "text" id = "address_box" value = ""/>
To display that data in your HTML text box, change your bindInfoWindow function, add code in there to put the data in the text box:
function bindInfoWindow(marker, map, infoWindow, html, name) {
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
document.getElementById("address_box").value = name;
});
}
And add name in to the call to it:
bindInfoWindow(marker, map, infoWindow, html, name);
Do you mean, when the infoWindow opens, you want to display some information into the textbox?
If so, this code might help you(I hope).
var infoWindow = new google.maps.InfoWindow;
var address_box = document.getElementById("address_box");
google.maps.event.addListener(infoWindow, "domready", function() {
address_box.value = infoWindow.get("Content");
});