JavaScript - Google Map Api V3 Marker Focus
Hey Guys,
I am currently building a web app that uses Google Maps V3 api. You select a check box which then shows a marker on the map. My issue is, when you select and the marker is placed, I need the map to focus to that point, it currently embeds but doesn't focus. Is there a particular function I could use to achieve this? My current code is shown below: Code: var locations = [ // Longitude, Latitue, Content, Country Code, City Name [51.481383, -3.114967, holidayOverlay, 'UK', 'Cardiff'], [52.362393, 4.893379, holidayOverlay, 'NL', 'Amsterdam'], [48.852314, 2.350089, holidayOverlay, 'FR', 'Paris'], [40.18884, -3.716812, holidayOverlay, 'SP', 'Madrid'], [53.800651, -4.064941, holidayOverlay, 'IT', 'Rome'], [42.041134, 1.889648, holidayOverlay, 'SP', 'Costa Brava'], [36.79334, 27.234421, holidayOverlay, 'GR', 'Kos'], [37.014581, -7.933888, holidayOverlay, 'PT', 'Algarve'], [28.358776, -14.05426, holidayOverlay, 'PT', 'Fuerteventura'], [29.046854, -13.589973, holidayOverlay, 'SP', 'Lanzarote'], ]; // Only create marker when checked for (i = 0; i < locations.length; i++) { if (locations[i][4] == location) { var marker = new google.maps.Marker({ position: new google.maps.LatLng(locations[i][0], locations[i][1]), map: map, icon: plotImage }); var title = locations[i][4]; var content = locations[i][2]; } } I have left a lot of the code out to save you a headache. Thanks. Similar Tutorialshi, on my site: http://www.sbannister.co.uk/helix_site2/contact.html I am able to move my logo on my map, is there any way of locking it's position? thanks Guy help me for the solution... how to refresh the markers only every x... below are my full scripts.... Code: <?php define('INCLUDE_CHECK',1); include "dbconnect.php"; ?> <!DOCTYPE html> <html lang="en"> <head> <script type="text/javascript" src="host_entry/js/jquery-1.7.1.min.js"></script> <!-- Google Map JS --> <script src="http://maps.google.com/maps/api/js?key=AIzaSyDY0kkJiTPVd2U7aTOAwhc9ySH6oHxOIYM&sensor=false" type="text/javascript"></script> </head> <div id="map_canvas" style="top:55px;left:13px;"> <!-- Map will display --> <div id="map"> <!-- Fullscreen Loading & Fullscreen Buttons area --> </div> <!-- Fullscreen Loading & Fullscreen Buttons area Ends --> </div><!-- Map Ends display --> <script type="text/javascript"> /**function show_data() { $('#map').load('index.php'); } setInterval('show_data()', 60000); **/ var locations = [ <?php $query="SELECT * from host_entry"; $result=mysql_query($query)or die(mysql_error()); { if ($num=mysql_numrows($result)) { $i=0; while ($i < $num) { $id=mysql_result($result,$i,"id"); //$host_type=mysql_result($result,$i,"host_type"); $host_name=mysql_result($result,$i,"host_name"); $host_server=mysql_result($result,$i,"host_server"); $host_status=mysql_result($result,$i,"host_status"); $host_lapt=mysql_result($result,$i,"host_lapt"); $host_long=mysql_result($result,$i,"host_long"); $host_circuit=mysql_result($result,$i,"host_circuit"); $host_hotline=mysql_result($result,$i,"host_hotline"); if($host_status==0) echo "['<div class=container style=width:400px;><div class=page-header><h4>$host_name</h4></div>', $host_lapt, $host_long],"; $i++; } }else { echo "<h3 align='center'><font color='#ff0000'>No Content Found</font></h3>"; } } ?> ]; // Setup the different icons and shadows var iconURLPrefix = 'host_entry/img/'; var icons = [ iconURLPrefix + 'p_red_alert.png' ] var icons_length = icons.length; var map = new google.maps.Map(document.getElementById('map'), { zoom: -5, center: new google.maps.LatLng(3.1215681, 101.71180140000001), mapTypeId: google.maps.MapTypeId.ROADMAP, mapTypeControl: false, streetViewControl: false, disableDefaultUI: true, panControl: false, zoomControlOptions: { position: google.maps.ControlPosition.LEFT_BOTTOM } }); var marker; var markers = new Array(); var iconCounter = 0; var infowindow = new google.maps.InfoWindow({ maxWidth: 400, maxHeight: 350, }); // Add the markers and infowindows to the map for (var i = 0; i < locations.length; i++) { marker = new google.maps.Marker({ position: new google.maps.LatLng(locations[i][1], locations[i][2], locations[i][3], locations[i][4], locations[i][5]), map: map, animation: google.maps.Animation.BOUNCE, icon : icons[iconCounter], }); markers.push(marker); google.maps.event.addListener(marker, 'click', (function(marker, i) { return function() { infowindow.setContent( locations[i][0] ); infowindow.open(map, marker); setTimeout(function(){infowindow.close();}, '5000'); } })(marker, i)); iconCounter++; // We only have a limited number of possible icon colors, so we may have to restart the counter if(iconCounter >= icons_length){ iconCounter = 0; } } function AutoCenter() { // Create a new viewpoint bound var bounds = new google.maps.LatLngBounds(); // Go through each... $.each(markers, function (index, marker) { bounds.extend(marker.position); }); // Fit these bounds to the map map.fitBounds(bounds); } AutoCenter(); </script> </body> </html> do i need to apply setInterval on the marker? how to apply it on the marker so it refresh every X second... please help for the solution.... I am having a problem with google maps api. i have created a map which will place a marker on the location entered in a text field. There are two other fields on the page called latbox and lngbox which i want to be populated when the marker is initially created and when it is dragged. so far im just working on the dragged and cant get it working although trying multiple ways. Code: <script type="text/javascript"> var geocoder; var map; var marker=false; function initialize() { geocoder = new google.maps.Geocoder(); var latlng = new google.maps.LatLng(-34.397, 150.644); var myOptions = { zoom: 8, center: latlng, mapTypeId: google.maps.MapTypeId.ROADMAP } map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); } function codeAddress() { var address = document.getElementById("address").value; geocoder.geocode( { 'address': address}, function(results, status) { if (status == google.maps.GeocoderStatus.OK) { map.setCenter(results[0].geometry.location); var marker = new google.maps.Marker({ map: map, position: results[0].geometry.location, draggable: true }); } else { alert("Geocode was not successful for the following reason: " + status); } }); } google.maps.event.addListener(marker, 'drag', function(event){ document.getElementById("latbox").value = event.latLng.lat(); document.getElementById("lngbox").value = event.latLng.lng(); }); </script> </head> <body onload="initialize()"> <div id="map_canvas" style="width:320px; height:320px"></div> <div> <input id="address" type="textbox" value="Sydney, NSW" /> <input type="button" value="Locate" onclick="codeAddress()" /> </div> <div id="latlong"> <p>Latitude: <input size="20" type="text" id="latbox" name="lat" ></p> <p>Longitude: <input size="20" type="text" id="lngbox" name="lng" ></p> </div> </body> </html> Any Help greatly appreciated Hi i am building a gps tracker and i am having problems with the marker manager. I am pretty new to this stuff and i am sure my problem is quiet simple i just cant get my head around it. I posted my java script . If anyone can help it will be much appreciated. I am adding marker data from an xml file generated. I want to add a marker manager to the already existing markers generated to i add extra functionality on them. thanks for your time. Code: Enter code here...<script type="text/javascript"> //<![CDATA[ ////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////// ///////////////////////////////CUSTOM ICONS///////////////////////////// ////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////// 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["restaurant"] = iconBlue; customIcons["bar"] = iconRed; ////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////// ///////////////////////////////END OF ICONS////////////////////////////// ///////////////////////////////////////////////////////////////////////// var map; // ////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////// //////////////////////////////////////INITIALIZE MAP//////////////////// function initialize () { if (GBrowserIsCompatible()) { map = new GMap2(document.getElementById("map_canvas")); map.enableScrollWheelZoom();/////ENABLES SCROLL ZOOM CONTROL ON THE MAP//// map.addControl(new GLargeMapControl());//ADD LARGE MAP CONTROL/////// map.addControl(new GMapTypeControl());///ADD MAP TYPE COTNROL/////// map.addMapType(G_PHYSICAL_MAP);//ADD PHYSICAL TERAIN MAP TYPE//////// //Latitude & Longitude of starting point in map, x,y,z--z represents zoom in the map// map.setCenter(new GLatLng(51.4595389, -0.243908),18); } } ////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////// //////////////////////////////////////END OF MAP///////////////////////// ////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////// GDownloadUrl("xtract.php", function(data) { var xml = GXml.parse(data); // Init the MarkerManager var batch =[]; mgr = new MarkerManager(map); var markers = xml.documentElement.getElementsByTagName("marker"); for (var i = 0; i < markers.length; i++) { var name = markers[i].getAttribute("id"); var address = markers[i].getAttribute("date"); var type = markers[i].getAttribute("mode"); var point = new GLatLng(parseFloat(markers[i].getAttribute("lat")), parseFloat(markers[i].getAttribute("lon"))); var marker = createMarker(point, name); batch.push(marker); mgr.addMarkers(batch,50); mgr.refresh(); map.addOverlay(marker); request.send(null); } }); ///////////////////////////////////////////////////// /////////////////////////////////////////////////////// function createMarker(posn, title, icon) { var marker = new GMarker(posn, {title: title, icon: icon, draggable:true }); GEvent.addListener(marker, 'dblclick', function() { mgr.removeMarker(marker) } ); return marker; } function deleteMarker() { var markerNum = parseInt(document.getElementById("id").value); mgr.removeMarker(allmarkers[markerNum]); } function clearMarkers() { mgr.clearMarkers(); } function reloadMarkers() { setupOfficeMarkers(); } </script> how can I get my custom markers to show? I have got my code in place, everything works except, doesn't show my custom marker?! here is my code: Code: <script type="text/javascript"> //<![CDATA[ if (GBrowserIsCompatible()) { // A function to create the marker and set up the event window // Dont try to unroll this function. It has to be here for the function closure // Each instance of the function preserves the contends of a different instance // of the "marker" and "html" variables which will be needed later when the event triggers. function createMarker(point,html) { var marker = new GMarker(point); GEvent.addListener(marker, "click", function() { marker.openInfoWindowHtml(html); marker.image = "images/google-pin.png"; marker.shadow = "images/google-pin-shadow.png"; marker.iconSize = new GSize(90, 70); marker.shadowSize = new GSize(90, 70); markerOptions = { icon:marker }; }); return marker; } // Display the map, with some controls and set the initial location var map = new GMap2(document.getElementById("map")); map.addControl(new GLargeMapControl()); map.addControl(new GMapTypeControl()); map.setCenter(new GLatLng(51.3992613899243,-1.32983778443008), 8); // Set up three markers with info windows var point = new GLatLng(51.4769752333875,-2.53517458867092); var marker = createMarker(point,'<div style="width:240px">Some stuff to display in the First Info Window. With a <a href="http:// www.econym.demon.co.uk">Link<\/a> to my home page<\/div>') map.addOverlay(marker); var point = new GLatLng(50.8391656924497,-0.154312843280554); var marker = createMarker(point,'Some stuff to display in the<br>Second Info Window') map.addOverlay(marker); var point = new GLatLng(50.8340528225749,-0.259947032613667); var marker = createMarker(point,'Some stuff to display in the<br>Third Info Window') map.addOverlay(marker); var point = new GLatLng(51.5168824045344,-2.6926718990779); var marker = createMarker(point,'Some stuff to display in the<br>Third Info Window') map.addOverlay(marker); var point = new GLatLng(50.954582894922,-0.145016932400171); var marker = createMarker(point,'Some stuff to display in the<br>Third Info Window') map.addOverlay(marker); } // display a warning if the browser was not compatible else { alert("Sorry, the Google Maps API is not compatible with this browser"); } // This Javascript is based on code provided by the // Community Church Javascript Team // http://www.bisphamchurch.org.uk/ // http://econym.org.uk/gmap/ //]]> </script> Hi, I am trying to add markers to Google Maps, they are working fine but some of the markers are of same location, thus Google Map will show only one marker for them. Is it possible to show all markers no matter if they are of same location. Help is much appreciated. Thanks I've been looking for a solid solution for how to add numbers to markers. Most that I've seen involve an asp page with a post back of an image based on the query string. I am trying to do something like what MarkerClusterer does. Here is an example: http://google-maps-utility-library-v...e_example.html I've looked over their code and cant seem to pull out the part where it adds the numbers to the marker, I'm still new to jquery. Here is a link to the source code: http://google-maps-utility-library-v...erclusterer.js any help would be appreciated. Would someone as be so kind to check my google maps script. For some reason the map is centering yet no marker (and info window) is being displayed. I'm (foolishly) using php to echo out the lat and long and the info window content yet everything seems to output okay...... Did a quick java de-bug and found the following error; Quote: Error: myLatlng is not defined Source File: xxx Line: 45 However the lat and lng are echo' out okay and the map is centered on the co-ordinates???? Much thanks!!!! Code: <script type="text/javascript"> function initialize() { var myOptions = { center: new google.maps.LatLng(53.989723,-7.361760), zoom: 13, mapTypeId: google.maps.MapTypeId.ROADMAP }; var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); var contentString = '<div>'+ '<h3 id="fs">Alcohol Early Intervention Project (Cavan/Monaghan)</h1>'+ '<div>'+ '<p>Click here for a streetview map</p>'+ '</div>'+ '</div>'; var infowindow = new google.maps.InfoWindow({ content: contentString }); var marker = new google.maps.Marker({ position: myLatlng, map: map, title:"Alcohol Early Intervention Project (Cavan/Monaghan)" }); var marker = new google.maps.Marker({ position: map.getCenter(), map: map, title: 'Click to zoom' }); google.maps.event.addListener(marker, 'click', function() { if (map.getZoom() == 13) { map.setZoom(4); } else { map.setZoom(8); } }); } </script> Right I have google maps connected to a database which holds stockists and their information. The user enters their postcode and radius and markers are put on the map of stockists in the radius of their postcode. I have this all working fine and the database chucks the information into an xml file fine. The problem im having is displaying the information in the pop up window of the marker. PHP Code: <script type="text/javascript"> //<![CDATA[ var map; var geocoder; function load() { if (GBrowserIsCompatible()) { geocoder = new GClientGeocoder(); map = new GMap2(document.getElementById('map')); map.addControl(new GSmallMapControl()); map.addControl(new GMapTypeControl()); map.setCenter(new GLatLng(54.622978,-2.592773), 5); } } function searchLocations() { var address = document.getElementById('addressInput').value; geocoder.getLatLng(address, function(latlng) { if (!latlng) { alert(address + ' not found'); } else { searchLocationsNear(latlng); } }); } function searchLocationsNear(center) { var radius = document.getElementById('radiusSelect').value; var searchUrl = 'phpsqlsearch_genxml.php?lat=' + center.lat() + '&lng=' + center.lng() + '&radius=' + radius; GDownloadUrl(searchUrl, function(data) { var xml = GXml.parse(data); var markers = xml.documentElement.getElementsByTagName('marker'); map.clearOverlays(); var sidebar = document.getElementById('sidebar'); sidebar.innerHTML = ''; if (markers.length == 0) { sidebar.innerHTML = 'No results found.'; map.setCenter(new GLatLng(54.622978,-2.592773), 5); return; } var bounds = new GLatLngBounds(); for (var i = 0; i < markers.length; i++) { var name = markers[i].getAttribute('name'); var address1 = markers[i].getAttribute('address1'); var address2 = markers[i].getAttribute('address2'); var town = markers[i].getAttribute('town'); var county = markers[i].getAttribute('county'); var postcode = markers[i].getAttribute('postcode'); var telephone = markers[i].getAttribute('telephone'); var distance = parseFloat(markers[i].getAttribute('distance')); var point = new GLatLng(parseFloat(markers[i].getAttribute('lat')), parseFloat(markers[i].getAttribute('lng'))); var marker = createMarker(point, name, address1, address2, town, postcode, telephone); map.addOverlay(marker); var sidebarEntry = createSidebarEntry(marker, name, town, distance); sidebar.appendChild(sidebarEntry); bounds.extend(point); } map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds)); }); } function createMarker(point, name, address1, address2, town, postcode, telephone) { var marker = new GMarker(point); var html = '<b>' + name + '</b> <br/>' + address1 + '<br />' + address2 + '<br />' + town + '<br />' + postcode + '<br />' + telephone; GEvent.addListener(marker, 'click', function() { marker.openInfoWindowHtml(html); }); return marker; } function createSidebarEntry(marker, name, town, distance) { var div = document.createElement('div'); var html = '<b>' + name + '</b> (' + distance.toFixed(1) + ')<br/>' + town; div.innerHTML = html; div.style.cursor = 'pointer'; div.style.marginBottom = '5px'; GEvent.addDomListener(div, 'click', function() { GEvent.trigger(marker, 'click'); }); GEvent.addDomListener(div, 'mouseover', function() { div.style.backgroundColor = '#eee'; }); GEvent.addDomListener(div, 'mouseout', function() { div.style.backgroundColor = '#fff'; }); return div; } //]]> </script> Example Xml: PHP Code: <markers> <marker name="AVON ANGLING CTR" address1="348 WHITEHALL ROAD" address2="ST. GEORGES" town="BRISTOL" county="AVON" postcode="BS5 7BP" telephone="01179 517250" lat="51.464432" lng="-2.546576" distance="0"/> <marker name="SCOTT TACKLE" address1="42 SOUNDWELL ROAD" address2="STAPLE HILL" town="BRISTOL" county="AVON" postcode="BS16 4QP" telephone="01179 567371" lat="51.477093" lng="-2.507667" distance="1.8894400025753"/> </markers> the only information displayed in the sidebar entry is the name and distance and on the marker just the name. Hello, I have the code below but for some reason it only works when adding the marker to the map (map click). When I drag the marker around, the coordinates and closest address don't update. This code works if I add the marker straight in the initialize() function but not when I add it within the addListenerOnce for map click event. I want to be able to add 1 marker to the map, and update its address and coordinates when dragging the marker around. If someone can help me sort this out... Thanks in advance! Code: <html> <head> <meta name="viewport" content="initial-scale=1.0, user-scalable=no" /> <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script> <script type="text/javascript"> var geocoder = new google.maps.Geocoder(); var marker; function geocodePosition(pos) { geocoder.geocode({ latLng: pos }, function(responses) { if (responses && responses.length > 0) { updateMarkerAddress(responses[0].formatted_address); } else { updateMarkerAddress('No matching address found.'); } }); } function updateMarkerStatus(str) { document.getElementById('markerStatus').innerHTML = str; } function updateMarkerPosition(latLng) { document.getElementById('info').innerHTML = [ latLng.lat(), latLng.lng() ].join(', '); } function updateMarkerAddress(str) { document.getElementById('address').innerHTML = str; } function initialize() { var latLng = new google.maps.LatLng(45.397, 2.644); var map = new google.maps.Map(document.getElementById('mapCanvas'), { zoom: 8, center: latLng, mapTypeId: google.maps.MapTypeId.ROADMAP }); google.maps.event.addListenerOnce(map, 'click', function(event) { var marker = new google.maps.Marker({ position: event.latLng, title: 'Nouveau marqueur', map: map, draggable: true }); // Update current position info. updateMarkerPosition(event.latLng); geocodePosition(event.latLng); }); // Add dragging event listeners. google.maps.event.addListener(marker, 'dragstart', function() { updateMarkerAddress('Dragging...'); }); google.maps.event.addListener(marker, 'drag', function() { updateMarkerStatus('Dragging...'); updateMarkerPosition(marker.getPosition()); }); google.maps.event.addListener(marker, 'dragend', function() { updateMarkerStatus('Drag ended'); geocodePosition(marker.getPosition()); }); } // Onload handler to fire off the app. google.maps.event.addDomListener(window, 'load', initialize); </script> </head> <body> <style> #mapCanvas { width: 500px; height: 400px; float: left; } #infoPanel { float: left; margin-left: 10px; } #infoPanel div { margin-bottom: 5px; } </style> <div id="mapCanvas"></div> <div id="infoPanel"> <b>Marker status:</b> <div id="markerStatus"><i>Click and drag the marker.</i></div> <b>Current position:</b> <div id="info"></div> <b>Closest matching address:</b> <div id="address"></div> </div> </body> </html> I've been trying for some time now to create some code which dynamically adds markers to a google map. I've now managed this but I still have a slight problem I think with the javascript side of things. I've included a snippet of the code which shows 2 markers on the map. They should be 2 different markers but they are the same, and the contents of the popup bubble should be each individual postcode, but they both show the same postcode. Does anyone have any ideas? Thanks Code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title>Geocoding UK Postcodes with Google APIs Demo</title> <style type="text/css"> html { height: 100%; } body { margin: 0; padding: 0; height: 100%; } #map { width: 100%; height: 100%; z-index:1; } </style> <script src="http://www.google.com/uds/api?file=uds.js&v=1.0&key=ABQIAAAAQJTCOfFBzEZfb0xYTu1h_BR0_9owy9VLLEJCKI_ZedHr-0NdXxQd9Q8sR1hC7s4PNGNVmIaTUQvspA" type="text/javascript"></script> <script src="http://maps.google.com/maps?file=api&v=2&sensor=false&key=ABQIAAAAQJTCOfFBzEZfb0xYTu1h_BR0_9owy9VLLEJCKI_ZedHr-0NdXxQd9Q8sR1hC7s4PNGNVmIaTUQvspA" type="text/javascript"></script> <script type="text/javascript"> //<![CDATA[ var icon2 = new GIcon(); icon2.image = "http://www.google.com/intl/en_us/mapfiles/ms/micons/blue-dot.png"; icon2.shadow = "http://www.google.com/mapfiles/shadow50.png"; icon2.iconSize = new GSize(32, 32); icon2.shadowSize = new GSize(37, 34); icon2.iconAnchor = new GPoint(16, 32); icon2.infoWindowAnchor = new GPoint(16, 0); var icon3 = new GIcon(); icon3.image = "http://www.google.com/intl/en_us/mapfiles/ms/micons/red-dot.png"; icon3.shadow = "http://www.google.com/mapfiles/shadow50.png"; icon3.iconSize = new GSize(32, 32); icon3.shadowSize = new GSize(37, 34); icon3.iconAnchor = new GPoint(16, 32); icon3.infoWindowAnchor = new GPoint(16, 0); var localSearch = new GlocalSearch(); function initialize() { if (GBrowserIsCompatible()) { map = new GMap(document.getElementById("map")); map.setCenter(new GLatLng(55.100651, -4.664941), 6); } } function createMarker(point2,html) { var marker2 = new GMarker(point2,icon2); GEvent.addListener(marker2, "click", function() { marker2.openInfoWindowHtml(html, { noCloseOnClick: true }); }); return marker2; } function createMarker2(point3,html) { var marker3 = new GMarker(point3,icon3); GEvent.addListener(marker3, "click", function() { marker3.openInfoWindowHtml(html, { noCloseOnClick: true }); }); return marker3; } //]]> </script> </head> <body> <div id="map"><script type="text/javascript">document.write(initialize())</script></div> <script type="text/javascript"> var thetext = 'LL58 8HU' localSearch.execute("LL58 8HU, UK"); localSearch.setSearchCompleteCallback(null, function() { map.addOverlay(createMarker(new GLatLng(localSearch.results[0].lat,localSearch.results[0].lng),thetext)); }); </script> <script type="text/javascript"> var thetext2 = 'RG4 6UT' localSearch.execute("RG4 6UT, UK"); localSearch.setSearchCompleteCallback(null, function() { map.addOverlay(createMarker2(new GLatLng(localSearch.results[0].lat,localSearch.results[0].lng),thetext2)); }); </script> </body> </html> Hi guys, Hopefully a really quick question. I'm a JS novice, and am looking for a way to output the coordinates of a Google maps marker into the value of two text fields, one for latitude and one for longitude. The code below is a simple location search which returns a result with a draggable marker. Currently, the coordinates in both text fields update when the location search is performed, but not when the marker is dragged to a new location afterwards. Does anyone know the code to simply update the coordinates each time the marker is dropped on a new location? Code: <html> <head> <style type="text/css"> #map_canvas { width:444px; height:444px; overflow:hidden; } </style> <script src="http://maps.google.com/maps?file=api&v=2&sensor=false&key=ABQIAAAA-Kl-tQOj5PlnOlXQmp2N9hTg6Fn61x9hOlvMvn6kV4ENK8yRfBShRuj-nulocuk2Alx9JmFKKV4zwA" type="text/javascript"></script> <script type="text/javascript"> var map; var geocoder; function initialize() { map = new GMap2(document.getElementById("map_canvas")); map.setCenter(new GLatLng(52.8068752, -1.6430344),6); map.addControl(new GLargeMapControl()); map.addControl(new GMapTypeControl()); map.enableScrollWheelZoom(); geocoder = new GClientGeocoder(); // Update current position info } // addAddressToMap() is called when the geocoder returns an // answer. It adds a marker to the map with an open info window // showing the nicely formatted version of the address and the country code. function addAddressToMap(response) { map.clearOverlays(); if (!response || response.Status.code != 200) { alert("Whoops, we couldn't find that address!"); } else { place = response.Placemark[0]; point = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]); marker = new GMarker(point,{draggable:true}); map.addOverlay(marker); marker.openInfoWindowHtml(place.address + '<br /><span class="smallgrey">Zoom in and drag the marker to exactly where the point is</span>'); document.getElementById("latitude").value = point.lat(); document.getElementById("longitude").value = point.lng(); } } // showLocation() is called when you click on the Search button // in the form. It geocodes the address entered into the form // and adds a marker to the map at that location. function showLocation() { var address = document.forms[0].q.value; geocoder.getLocations(address, addAddressToMap); } // findLocation() is used to enter the sample addresses into the form. function findLocation(address) { document.forms[0].q.value = address; showLocation(); } </script> </head> <body onload="initialize()"> <form action="#" onsubmit="showLocation(); return false;"><input type="text" name="q" size="35" /> <input type="submit" name="find" value="Search"/></form> <div id="map_canvas">And pin the <strike>tail</strike> marker on the <strike>donkey</strike> map:<br /></div> Latitude: <input class="required" type="text" name="latitude" id="latitude" value="53.34870686020199" /> <br /> Longitude: <input class="required" type="text" name="longitude" id="longitude" value="-6.267356872558594" /> </body> </html> Many thanks in advance, I appreciate anyone who wants to help out! Hi I'm banging my head against this problem and I'd really appreciate some help. I think the problem is cause by my lack of understanding of how the browser (firefox 3.6.3) handles focus. A simplified version of my problem is: I've defined the function Code: function two_focus() { document.getElementById("two").blur(); alert("hello"); } then in the body I have the form with two text boxes Code: <input id="one" type="text"><input id="two" type="text" onfocus="two_focus();"> When the page is loaded and I click in the second textbox I get the alert, all well and good. I OK the alert box, but when I click on box 1, or anywhere on the page for that matter, the function is called and the alert comes up. I just don't understand why the focus is being returned to the second box when I click anywhere in the browser window. Any comments will be gratefully received. This is some of the script that I have and it works well. The story is that I have a drop down list and depending on the selection a different set of text is displayed below the list. Code: if (Val == "general") { document.getElementById('Link0').innerHTML="<font size=2><a Href='http://www.web1.com/'>web 1</a>" document.getElementById('Link1').innerHTML="<font size=2><a Href='http://www.web2.com/'>web 2</a>" However when the selection runs this part of the code:- Code: if (Val == "duties") { document.getElementById('Link0').innerHTML="" document.getElementById('Link1').innerHTML="<font size=2><a Href='http://www.web2.com/'>web3</a>" The "web 3" text is placed under where the 'Link0' text would have been if there had been some. So basically what I need to do is set the 'Link0' text to nothing and have the 'Link1' text sit in its place. I know I could just put the 'Link1' text in the 'Link0' element but I have other controls on the screen that mean I need to run it as it is. I hope that is clear, cheers Daniel. I have a page with a GoogleMap with a GoogleBar and I would like the GoogleBar to appear with something written in it already and to have that search executed. In other words, I would like to "write something to the GoogleBar and press Enter" automatically as soon as the map loads. How can I do this? btw: By GoogleBar, I mean the search bar that appears on the map after using the enableGoogleBar() function. Hi, I'm not sure where I have translated this incorrectly. I have one google map embedded on my page which works fine. But I wanted to add a second one. I thought the easiest way to do this would be to have a second page which is called later on with all the details on it for the second map. However although I think (this I presume is where I went wrong) I have replicated the instructions correctly the place holder for the second map just remains blank. This is the code for my called page with the instructions for the second map: PHP Code: <?php echo $_POST['Map'] . '<br />'; ?> <div id="placemap_canvas"></div> <meta name="viewport" content="initial-scale=1.0, user-scalable=no" /> <style type="text/css"> html {height:250px} body {height:250px} #placemap_canvas {width:100%; height:150px;} </style> <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true" /> </script> <script type="text/javascript"> var latlng = new google.maps.LatLng ( <?php include("dbconnect.php"); $result = mysql_query("SELECT * FROM regions WHERE RegionPId='{$_POST['Map']}'"); while($row = mysql_fetch_array($result)){ echo $row['maplink']; } mysql_close($con); ?> ); var myOptions = { zoom: 4, center: latlng, mapTypeId: google.maps.MapTypeId.ROADMAP }; var map = new google.maps.Map(document.getElementById("placemap_canvas"), myOptions); } </script> And this is the script of the main page, just in case I would be better off keeping them both in one place. Code: <head> <script type="text/javascript"> function loadSubPlace(File,ID,Msg,Eile,EID,Esg){ loadXMLDoc1(File,ID,Msg); var mimer = setTimeout(function(){loadXMLDoc1(Eile,EID,Esg)},5000); } </script> <meta name="viewport" content="initial-scale=1.0, user-scalable=no" /> <style type="text/css"> html {height:250px} body {height:250px} #map_canvas {width:30%; height:250px;} </style> <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true" /> </script> <script type="text/javascript"> function initialize() { var latlng = new google.maps.LatLng ( <?php include("dbconnect.php"); $result = mysql_query("SELECT * FROM countries WHERE Country='{$_SESSION['Country']}'"); while($row = mysql_fetch_array($result)){ echo $row['Map']; } mysql_close($con); ?>); var myOptions = { zoom: 4, center: latlng, mapTypeId: google.maps.MapTypeId.ROADMAP }; var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); } </script> </head> <body onload="initialize()"> <div class="countryright" id="map_canvas"> include("dbconnect.php"); $snowball=explode(';',$_POST['syringa']); $turnsol=$snowball[1]; $violet =$snowball[2]; $wakerobin=$snowball[3]; global $turnsol; global $violet; global $wakerobin; echo '<center><b><big>' . $wakerobin. '</big></b></center><br /><br />'; $result=mysql_query("SELECT * FROM regions WHERE country='{$turnsol}' AND region='{$violet}' AND place='{$wakerobin}' AND sub !='' ORDER BY sub ASC"); while($row = mysql_fetch_array($result)){ $wheat="{$row['RegionPId']};{$turnsol};{$violet};{$wakerobin};{$row['sub']}"; $tigerlilly=$row['RegionPId']; echo '<input type="button" class="button3" name="place" id="place" value="' . $row['sub'] . '" onclick="loadSubPlace(\'getPlace.php\',\'txtHintPlaceSub\',\'hepatica=' . urlencode($wheat) . '\',\'getPlaceMap.php\',\'placemapcanvas\',\'Map=' . urlencode($tigerlilly) . '\');" />'; } echo '<input type="button" class="button3" name="addplace" id="addplace" value="Add Place" onclick="loadXMLDoc1(\'getAddPlaceSub.php\',\'txtHintPlaceSub\', encodeURI(\'addsubplace=' . $_POST['syringa'] . '\'));" />'; echo '<br /><br /><div id="txtHintPlaceSub"></div><br /><br />'; mysql_close($con); ?> I've cut out the script that doesn't relate to this so I hope I haven't missed anything important. Everything up until the focus line works, any ideas? Code: else { alert ("Please enter your Postcode correctly, this includes:\n \n * Correct Spacing - AA1 1AA \n * Correct amount of letters and numbers. \n \n Sorry if this causes any inconvenience, but it is to your benefit."); document.delAdd.postcode.value = ""; document.delAdd.postcode.focus();} Have a jsp page with 10 editable fields and in last Add Button.Now when user edit a field from value 10 to 20(example)and click on Add .Value will be changed and focus will return to the same field.similarly for other fields.how to to .any code sample?
Hi I am opening a child window with the following href. If it is a completly new window, it is opened and the focus shifts to it, ... but ... if that href has been clicked on before and the window exists, the focus stays with the parent window and does NOT shift to the child How can I make the focus shift ? here is my href: PHP Code: echo "<a href='$Ad_detail' rel=\"external\" onclick=\"window.open (this.href, '$Ad_detail', 'height=800,width=960,scrollbars'); return false\" > I guess I need a "window. ??? focus();" in there somewhere - but I don't know what the ??? should be. If you can help - many thanks Hy ! I have this form: PHP Code: <form name = "myform" method = "POST" action = "proba1.php"> Name:<br /> <input type = "text" name = "name" size = "30" onBlur = "namecheck()" /><br /> Username:<br /> <input type = "text" name = "username" size = "30" onBlur = "usercheck()" /><br /> Password:<br /> <input type = "password" name = "password" size = "30" /><br /> Repeat password:<br /> <input type = "password" name = "password2" size = "30" onBlur = "passcheck()"/><br /> Email:<br /> <input type = "text" name = "email" size = "30" onBlur = "mailcheck()" /><br /><br /> <input type = "reset" name = "reset" value = "Reset" /> <input type = "submit" name = "submit" value = "Submit" /> </form> and a Js file to check it: PHP Code: function namecheck() { var name = document.myform.name.value; if(name.indexOf(" ") < 0) { document.myform.name.focus(); document.myform.name.select(); alert("Pleaase enter your full name!") return false; } return true; } function usercheck() { var username = document.myform.username.value; if(username.length < 6) { alert("Username must be at least 6 chars!"); document.myform.name.focus(); document.myform.name.select(); return false; } return true; } function passcheck() { var password = document.myform.password.value; var password2 = document.myform.password2.value; if(password != password2) { alert("The two passwords not identical!") } } function mailcheck() { var mail = document.myform.email.value; var diff = mail.lastIndexOf(".") - mail.indexOf("@"); var diff2 = mail.length - mail.lastIndexOf("."); if(mail.indexOf("@") < 0 || mail.indexOf(".") < 0 || diff < 2 || diff2 > 3) { alert("Not a valid email adress!") } } So when a value is not proper,there should be an alert message,then select and focus on the field.But only the alert works.I can set the select and the focus to any other field from the current one ,but not to the current.(For instance:if the name is not good:document.myform.username.select() works,but :document.myform.name.select() not.) Can somebody help me? |