Solved

Google Maps Page not working

Posted on 2013-01-18
10
462 Views
Last Modified: 2013-01-22
Hello,

I have the following code which is not giving the desired result...!  I get a non-centered map with no pins, whereas I am hoping for a map that is centered on a country and pins dropped in the map from the sample XML shown in the code!  The country name to center the map on is taken from a form hidden field...

The output can be seen here: http://www.villasdirect.com/_admin/dev/country_map.asp

<%@LANGUAGE="VBSCRIPT" CODEPAGE="65001"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
  <head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
    <title>Google Maps</title>
    <script src="http://maps.google.com/maps?file=api&amp;v=2&amp;sensor=false&amp;key=AIzaSyDxVVqM06Tyh5J_lnz8JWDWDHVjH9KPq38" type="text/javascript"></script>
  </head>
  <body onunload="GUnload()" onload="showAddress(); return false">

    <div id="map" style="width: 800px; height: 600px"></div>
  
    <form onsubmit="showAddress(); return false" action="#">
      <input id="search" size="60" type="hidden" value="France" />
    </form>
        
    <div id="message"></div>

    <noscript><b>JavaScript must be enabled in order for you to use Google Maps.</b> 
      However, it seems JavaScript is either disabled or not supported by your browser. 
      To view Google Maps, enable JavaScript by changing your browser options, and then 
      try again.
    </noscript>

    <script type="text/javascript">
    //<![CDATA[
	var xmlsource = '<markers><marker Town="Fayence" Region="Provence - Var" type="green" lng="6.694103" lat="43.624076"/><marker Town="La Cadiere  d\'Azur" Region="Provence - Var" type="green" lng="5.755173" lat="43.196218"/><marker Town="Villefranche Du Périgord" Region="South West France" type="green" lng="1.080006" lat="44.62966"/><marker Town="Limetz-Villez" Region="Paris" type="green" lng="1.547366" lat="49.029137"/><marker Town="Boulogne-Billancourt" Region="Paris" type="green" lng="2.237803" lat="48.84325"/><marker Town="Saint-Germain-En-Laye" Region="Paris" type="green" lng="2.0934031" lat="48.8955155"/></markers>'
    
    if (GBrowserIsCompatible()) { 

      var map = new GMap(document.getElementById("map"));
   	  map.addControl(new GLargeMapControl());
      map.addControl(new GMapTypeControl());
      map.setCenter(new GLatLng(20,0),2);

	  var infoWindow = new google.maps.InfoWindow;
	  $( $.parseXML( xmlsource ) ).find("marker").each(function() {
	  var lng = $(this).attr('lng');
	  var lat = $(this).attr('lat');
	  marker = new google.maps.Marker({
      map:map,
      draggable:true,
      animation: google.maps.Animation.DROP,
      position: new google.maps.LatLng(59.32522, 18.07002)
    });
    google.maps.event.addListener(marker, 'click', toggleBounce);
	  }
      
      
      // ====== Create a Client Geocoder ======
      var geo = new GClientGeocoder(); 

      // ====== Array for decoding the failure codes ======
      var reasons=[];
      reasons[G_GEO_SUCCESS]            = "Success";
      reasons[G_GEO_MISSING_ADDRESS]    = "Missing Address: The address was either missing or had no value.";
      reasons[G_GEO_UNKNOWN_ADDRESS]    = "Unknown Address:  No corresponding geographic location could be found for the specified address.";
      reasons[G_GEO_UNAVAILABLE_ADDRESS]= "Unavailable Address:  The geocode for the given address cannot be returned due to legal or contractual reasons.";
      reasons[G_GEO_BAD_KEY]            = "Bad Key: The API key is either invalid or does not match the domain for which it was given";
      reasons[G_GEO_TOO_MANY_QUERIES]   = "Too Many Queries: The daily geocoding quota for this site has been exceeded.";
      reasons[G_GEO_SERVER_ERROR]       = "Server error: The geocoding request could not be successfully processed.";
      
      // ====== Geocoding ======
      function showAddress() {
        var search = document.getElementById("search").value;
        // ====== Perform the Geocoding ======        
        geo.getLocations(search, function (result)
          { 
            // If that was successful
            if (result.Status.code == G_GEO_SUCCESS) {
              // How many resuts were found
              document.getElementById("message").innerHTML = "Found " +result.Placemark.length +" results";
              // Loop through the results, placing markers
              for (var i=0; i<result.Placemark.length; i++) {
                var p = result.Placemark[i].Point.coordinates;
                var marker = new GMarker(new GLatLng(p[1],p[0]));
                document.getElementById("message").innerHTML += "<br>"+(i+1)+": "+ result.Placemark[i].address + marker.getPoint();
                map.addOverlay(marker);
              }
              // centre the map on the first result
              var p = result.Placemark[0].Point.coordinates;
              // ===== Look for the bounding box of the first result =====
              var N = result.Placemark[0].ExtendedData.LatLonBox.north;
              var S = result.Placemark[0].ExtendedData.LatLonBox.south;
              var E = result.Placemark[0].ExtendedData.LatLonBox.east;
              var W = result.Placemark[0].ExtendedData.LatLonBox.west;
              var bounds = new GLatLngBounds(new GLatLng(S,W), new GLatLng(N,E));
              // Choose a zoom level that fits
              var zoom = map.getBoundsZoomLevel(bounds);

              map.setCenter(bounds.getCenter(),zoom);

              var points=[new GLatLng(N,W),new GLatLng(N,E),new GLatLng(S,E),new GLatLng(S,W),new GLatLng(N,W)];
              map.addOverlay(new GPolyline(points));

            }
            // ====== Decode the error status ======
            else {
              var reason="Code "+result.Status.code;
              if (reasons[result.Status.code]) {
                reason = reasons[result.Status.code]
              } 
              alert('Could not find "'+search+ '" ' + reason);
            }
          }
        );
      }
    }
    
    // display a warning if the browser was not compatible
    else {
      alert("Sorry, the Google Maps API is not compatible with this browser");
    }
    </script>
  </body>

</html>

Open in new window


THANK YOU!
0
Comment
Question by:Nico2011
10 Comments
 
LVL 38

Expert Comment

by:Tom Beck
ID: 38793914
Step one: Lose that version 2 code and start using version 3 of the Google Maps API. Here's an example of centering on a country using v3 API.
<!DOCTYPE html>
<html> 
<head> 
   <meta http-equiv="content-type" content="text/html; charset=UTF-8"/> 
   <title>Google Maps fitBounds</title> 
   <script src="http://maps.google.com/maps/api/js?sensor=false" 
           type="text/javascript"></script> 
</head> 
<body> 
   <div id="map" style="width: 900px; height: 500px;"></div> 

   <script type="text/javascript"> 
      var myOptions = {
		zoom: 4,		
	  	mapTypeId: google.maps.MapTypeId.ROADMAP
	  };
      var map = new google.maps.Map(document.getElementById("map"), myOptions);
      var geocoder = new google.maps.Geocoder();

      geocoder.geocode({'address': 'US'}, function (results, status) {
         var ne = results[0].geometry.viewport.getNorthEast();
         var sw = results[0].geometry.viewport.getSouthWest();

         map.fitBounds(results[0].geometry.viewport);               
      }); 
   </script> 
</body> 
</html>

Open in new window

0
 

Author Comment

by:Nico2011
ID: 38794007
Thanks - the version I have auto zooms to fit the location into the screen (or is supposed to!) - it fell apart when I added my pins... and parsed my XML.

Not sure if I would know where to start to get the auto zoom to get the map to the right size and parse the XML with 'Step 1'!  Are there more steps to follow...? (please!)
0
 
LVL 38

Expert Comment

by:Tom Beck
ID: 38794252
Here's a working version of what you are trying to do. It uses v3 of the API. I gave you a way to change marker colors by checking the "type" attribute in the xml. Also a way to display "Region" and "town".
<%@LANGUAGE="VBSCRIPT" CODEPAGE="65001"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
  <head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
    <title>Google Maps</title>
	<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
    <script src="http://maps.google.com/maps/api/js?sensor=false" 
           type="text/javascript"></script> 
  </head>
  <body>

    <div id="map" style="width: 800px; height: 600px"></div>
  
    <form onsubmit="showAddress(); return false" action="#">
      <input id="search" size="60" type="hidden" value="France" />
    </form>
        
    <div id="message"></div>

    <noscript><b>JavaScript must be enabled in order for you to use Google Maps.</b> 
      However, it seems JavaScript is either disabled or not supported by your browser. 
      To view Google Maps, enable JavaScript by changing your browser options, and then 
      try again.
    </noscript>

    <script type="text/javascript">
    //<![CDATA[
       
    
	var xmlsource = '<markers><marker Town="Fayence" Region="Provence - Var" type="green" lng="6.694103" lat="43.624076"/><marker Town="La Cadiere  d\'Azur" Region="Provence - Var" type="green" lng="5.755173" lat="43.196218"/><marker Town="Villefranche Du Périgord" Region="South West France" type="green" lng="1.080006" lat="44.62966"/><marker Town="Limetz-Villez" Region="Paris" type="green" lng="1.547366" lat="49.029137"/><marker Town="Boulogne-Billancourt" Region="Paris" type="green" lng="2.237803" lat="48.84325"/><marker Town="Saint-Germain-En-Laye" Region="Paris" type="green" lng="2.0934031" lat="48.8955155"/></markers>'
    
	var myOptions = {
		zoom: 4,
	  	mapTypeId: google.maps.MapTypeId.ROADMAP
	  };
      var map = new google.maps.Map(document.getElementById("map"), myOptions);

	  var infoWindow = new google.maps.InfoWindow;
	  $( $.parseXML( xmlsource ) ).find("marker").each(function() {
	  	var lng = $(this).attr('lng');
	  	var lat = $(this).attr('lat');
	  	marker = new google.maps.Marker({
      		map:map,
      		draggable:true,
      		animation: google.maps.Animation.DROP,
      		position: new google.maps.LatLng(59.32522, 18.07002)
      	});
	  });
      google.maps.event.addListener(marker, 'click');
	
      // ====== Create a Client Geocoder ======
      var geo = new google.maps.Geocoder(); 
	  geo.geocode({'address': document.getElementById("search").value}, function (results, status) {
         var ne = results[0].geometry.viewport.getNorthEast();
         var sw = results[0].geometry.viewport.getSouthWest();

         map.fitBounds(results[0].geometry.viewport); 
		 placeMarkers();              
      }); 
	  
	  function placeMarkers(){
	  	var xmlList = $.parseXML(xmlsource);
		var markers = $(xmlList).find('marker');
		for (var i = 0; i < markers.length; i++) {
        var latlng = new google.maps.LatLng(parseFloat($(markers[i]).attr("lat")),
                                    parseFloat($(markers[i]).attr("lng")));
		var type = $(markers[i]).attr("type");
		var imgnam = "";
		if(type == "green")	{
			imgnam = "http://openmbta.org/images/map/PinDown1Green.png?1306943843";
		}else{
			imgnam = "http://openmbta.org/images/map/PinDown1.png?1306943843";
		}		
		var img = new google.maps.MarkerImage(
			imgnam,
			new google.maps.Size(30,35),
			new google.maps.Point(0,0),
			new google.maps.Point(15,35)
		);
		//add a link to your xml that can be inserted here where I have http://www.google.com
		var html = "<a href='http://www.google.com'>" + $(markers[i]).attr('Region') + ', ' + $(markers[i]).attr('Town') + "</a>";									
        var marker = new google.maps.Marker({position: latlng, map: map, icon: img, html:html});
		
		var infowindow1 = new google.maps.InfoWindow();
		google.maps.event.addListener(marker, 'mouseover', function() {
			infowindow1.setContent(this.html);
	        infowindow1.open(map, this);
	    });
		}
		  
	  }

    </script>
  </body>

</html>

Open in new window

0
Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

 
LVL 38

Accepted Solution

by:
Tom Beck earned 500 total points
ID: 38800871
Has this been question answered to your satisfaction?
0
 

Author Closing Comment

by:Nico2011
ID: 38800897
Yes thank you for your help.  I did have a complaint from 'Sedgwick' as I awarded all points to you for the other question which you answered, so I think I've made an enemy there!

Anyhow - your answer was 100% correct, so thank you again.
0
 
LVL 38

Expert Comment

by:Tom Beck
ID: 38800917
Thanks for the points.

You can still split the points on the other question if @Sedgwick contributed to the answer. Just click "Request Attention" on the other question and explain how you would like to modify the awarding of points to the moderator.
0
 
LVL 42

Expert Comment

by:sedgwick
ID: 38800927
i'm here, 10x for splitting the points
0
 

Author Comment

by:Nico2011
ID: 38800929
thanks for letting me know that - will do!
0
 
LVL 109

Expert Comment

by:Ray Paseur
ID: 38801701
@tommyBoy:

Really excellent example, and a model of why I use EE.  

I wonder if you would consider publishing an article here at EE explaining the process and providing some code examples.  I did one a couple of years ago on the Google Static Maps, example here:
www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_3350.html

Best regards, and thanks for a great contribution to the community, ~Ray
0
 
LVL 38

Expert Comment

by:Tom Beck
ID: 38806107
Thanks for the kind words Ray. I will consider the article idea. I have not done that yet. Still building confidence. I always feel a little out of my league with all the professional programmers on EE. Web development is still an infrequent part of my daily routine.
0

Featured Post

3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

This article will give core knowledge of JavaScript and will head in to your first JavaScript program. I am Durvesh Naik and I am here to deal with this series of JavaScript. I will teach you JavaScript in part wise , as its quite boring to read big…
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

773 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question