• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 513
  • Last Modified:

Google Maps Page not working

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
Nico2011
Asked:
Nico2011
1 Solution
 
Tom BeckCommented:
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
 
Nico2011Author Commented:
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
 
Tom BeckCommented:
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
Cloud Class® Course: Microsoft Azure 2017

Azure has a changed a lot since it was originally introduce by adding new services and features. Do you know everything you need to about Azure? This course will teach you about the Azure App Service, monitoring and application insights, DevOps, and Team Services.

 
Tom BeckCommented:
Has this been question answered to your satisfaction?
0
 
Nico2011Author Commented:
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
 
Tom BeckCommented:
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
 
Meir RivkinFull stack Software EngineerCommented:
i'm here, 10x for splitting the points
0
 
Nico2011Author Commented:
thanks for letting me know that - will do!
0
 
Ray PaseurCommented:
@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
 
Tom BeckCommented:
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
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: Microsoft Office 2010

This course will introduce you to the interfaces and features of Microsoft Office 2010 Word, Excel, PowerPoint, Outlook, and Access. You will learn about the features that are shared between all products in the Office suite, as well as the new features that are product specific.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now