11953

Passing XML to Javascript to show markers in Google map

Question:

I'm a newbie to php and I'm trying to create a Google map based on this tutorial <a href="https://developers.google.com/maps/articles/phpsqlajax_v3" rel="nofollow">https://developers.google.com/maps/articles/phpsqlajax_v3</a> with a little twist. I've put up a search box and managed to output an XML based on the query.

I'm having a hard time passing the XML data from search.php to make markers in Google maps

here's my code

<strong>for the form</strong>

<form name="form1" method="POST" action="search.php"> <input type="text" name="search" size="20"/> <input type="button" onClick="searchLocations()" value="Search"/> </form>

<strong>For the search.php</strong>

<?php include("config.php"); function parseToXML($htmlStr) { $xmlStr=str_replace('<','&lt;',$htmlStr); $xmlStr=str_replace('>','&gt;',$xmlStr); $xmlStr=str_replace('"','&quot;',$xmlStr); $xmlStr=str_replace("'",'&#39;',$xmlStr); $xmlStr=str_replace("&",'&amp;',$xmlStr); return $xmlStr; } if(empty($_POST['search'])) { header("Location:map.html"); } $query = " SELECT * FROM markers WHERE name LIKE '%".$_POST['search']."%' OR address LIKE '%".$_POST['search']."%' "; $result = mysql_query($query); if (!$result) { die("Invalid query: " . mysql_error()); } header("Content-type: text/xml"); // Start XML file, echo parent node echo '<markers>'; // Iterate through the rows, printing XML nodes for each while ($row = @mysql_fetch_assoc($result)){ // ADD TO XML DOCUMENT NODE echo '<marker '; echo 'name="' . parseToXML($row['name']) . '" '; echo 'address="' . parseToXML($row['address']) . '" '; echo 'lat="' . $row['lat'] . '" '; echo 'lng="' . $row['lng'] . '" '; echo 'type="' . $row['type'] . '" '; echo '/>'; } // End XML file echo '</markers>'; ?>

<strong>For the javascript</strong>

<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script> <script type="text/javascript"> //<![CDATA[ var customIcons = { restaurant: { icon: 'http://labs.google.com/ridefinder/images/mm_20_blue.png' }, bar: { icon: 'http://labs.google.com/ridefinder/images/mm_20_red.png' } }; function load() { var map = new google.maps.Map(document.getElementById("map"), { center: new google.maps.LatLng(14.479, 121.020), zoom: 14, mapTypeId: 'roadmap' }); var infoWindow = new google.maps.InfoWindow; // Change this depending on the name of your PHP file downloadUrl("search.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/>" + address; var icon = customIcons[type] || {}; var marker = new google.maps.Marker({ map: map, position: point, icon: icon.icon }); 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); }); } function downloadUrl(url, callback) { var request = window.ActiveXObject ? new ActiveXObject('Microsoft.XMLHTTP') : new XMLHttpRequest; request.onreadystatechange = function() { if (request.readyState == 4) { request.onreadystatechange = doNothing; callback(request, request.status); } }; request.open('GET', url, true); request.send(null); } function doNothing() {} //]]> </script>

Answer1:

<blockquote> <ul><li><strong>demo:</strong> <a href="http://so.devilmaycode.it/passing-xml-to-javascript-to-show-markers-in-google-map" rel="nofollow">http://so.devilmaycode.it/passing-xml-to-javascript-to-show-markers-in-google-map</a></li> </ul></blockquote>

html

<!DOCTYPE html > <head> <title</title> <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script> <script type="text/javascript"> //<![CDATA[ var map = null; var customIcons = { restaurant: { icon: 'http://labs.google.com/ridefinder/images/mm_20_blue.png' }, bar: { icon: 'http://labs.google.com/ridefinder/images/mm_20_red.png' } }; function load() { map = new google.maps.Map(document.getElementById("map"), { center: new google.maps.LatLng(47.6145, -122.3418), zoom: 13, mapTypeId: 'roadmap' }); } function bindInfoWindow(marker, map, infoWindow, html) { google.maps.event.addListener(marker, 'click', function() { infoWindow.setContent(html); infoWindow.open(map, marker); }); } function searchLocations(){ var infoWindow = new google.maps.InfoWindow; var search_term = document.getElementById('search-term').value; jQuery.ajax({ dataType :'xml', type: 'GET', url : 'search.php?search_term='+search_term, success:function(data){ var markers = data.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/>" + address; var icon = customIcons[type] || {}; var marker = new google.maps.Marker({ map: map, position: point, icon: icon.icon }); bindInfoWindow(marker, map, infoWindow, html); } }}); return false; } //]]> </script> </head> <body onload="load()">

<form id="search-form" method="post" action="search.php"> <input type="text" name="search" size="20" id="search-term"/> <input type="button" value="Search" onclick="searchLocations();" /> </form>

<div id="map" style="width: 500px; height: 300px"></div> </body> </html>

php

<?php include("config.php"); function xml_entities($value) { return strtr( $value, array( "<" => "&lt;", ">" => "&gt;", '"' => "&quot;", "'" => "&apos;", "&" => "&amp;", ) ); } if(isset($_REQUEST['search_term'])){ $search_term = mysql_real_escape_string(trim($_REQUEST['search_term'])); if($result = mysql_query("SELECT * FROM markers WHERE name LIKE '%{$search_term}%' OR address LIKE '%{$search_term}%'")){ $markers = array(); while ($row = @mysql_fetch_assoc($result)){ extract($row); $markers[] = "<marker name='".xml_entities($name)."' address='".xml_entities($address)."' lat='{$lat}' lng='{$lng}' type='{$type}' />"; } if(count($markers)){ header("Content-type: text/xml"); echo '<markers>'.implode('', $markers).'</markers>'; } } } ?>

Recommend

  • Uncaught TypeError: Object [object Object] has no method 'fancybox'
  • Notice: Undefined index: image - unable to find the error
  • Can't connect using mysql_connect to Database in ipage.com hosting?
  • How to get the second value in a dropdown box based on the selected one in the first dropdown box
  • Insert records into two table at once
  • Disable add to cart redirection
  • Crafting a LINQ based solution to determine if a set of predicates are satisfied for a pair of colle
  • how to remove a div with same ids but display='block' and display='none' in JAVa
  • Passing parameter through “window.location.href”
  • JSON - slashes not escaping
  • PDO error when wrong host name
  • Randomizing -and remembering that randomisation- multiple choice questions in php
  • In loopback documentation what does variable 'cb' stands for?
  • Simple linked list-C
  • msbuild create itemgroup from property group
  • Updating both a ConcurrentHashMap and an AtomicInteger safely
  • CakePHP ACL tutorial initDB function warnings
  • Force show.bind execution
  • Play WS (2.2.1): post/put large request
  • Disable Enter in editText android
  • Exception “firebase.functions() takes … no argument …” when specifying a region for a Cloud Function
  • Using variable in a value field in jMeter
  • Using $this when not in object context
  • How to make a tree having multiple type of nodes and each node can have multiple child nodes in java
  • DotNetZip - Calculate final zip size before calling Save(stream)
  • Deserializing XML into class C#
  • Display Images one by one with next and previous functionality
  • Warning: Can't call setState (or forceUpdate) on an unmounted component
  • Numpy divide by zero. Why?
  • Is there a mandatory requirement to switch app.yaml?
  • using conditional logic : check if record exists; if it does, update it, if not, create it
  • Load html files in TinyMce
  • python regex in pyparsing
  • Free memory of cv::Mat loaded using FileStorage API
  • Android Google Maps API OnLocationChanged only called once
  • Linking SubReports Without LinkChild/LinkMaster
  • Easiest way to encapsulate a HTML5 webpage into an android app?
  • How can i traverse a binary tree from right to left in java?
  • How to Embed XSL into XML
  • How can I use threading to 'tick' a timer to be accessed by other threads?