0

I wonder whether someone may be able to help me please.

I've put together this page which allows a user to geocode an address, either via a map click or by manually typing the address, and this works as expected. This code is a slight adaption of a tutorial found here.

What I'm now trying to do, in addition to the above functionality, is add code which places a marker with co-ordinates already held in a MySQL database.

This is the code which I've put together to try and achieve this:

<script type="text/javascript">

         var icon = new google.maps.MarkerImage("images/location-marker-2.png")
         new google.maps.Point(16, 32);
         var center = null;
         var map = null;
         var bounds = new google.maps.LatLngBounds();
         function addMarker(lat, lng, info) {
         var pt = new google.maps.LatLng(lat, lng);
         bounds.extend(pt);
         var marker = new google.maps.Marker({
         position: pt,
         icon: icon,
         map: map
         });
         }
         function initMap() {
         map = new google.maps.Map(document.getElementById("gmaps-canvas"), {
         center: new google.maps.LatLng(0, 0),
         zoom: 6,
         scrollwheel: true,     
         draggable: true, 
         mapTypeId: google.maps.MapTypeId.SATELLITE
         });
            <?php

                    include("admin/link.php");
                    include("admin/opendb.php");

                    $query = mysql_query("SELECT * FROM `detectinglocations` WHERE `locationid` = '$lid'");
                    while ($row = mysql_fetch_array($query)){
                        $locationname=$row['locationname'];
                        $osgb36lat=$row['osgb36lat'];
                        $osgb36lon=$row['osgb36lon'];
                        echo ("addMarker($osgb36lat, $osgb36lon,'<b>$locationname</b><br/>');\n");
                    }
                         mysql_close($connect);
             ?>

                     center = bounds.getCenter();
                     map.fitBounds(bounds);
                 }
</script> 

The problem I'm having is that I can get the geocode functionality to work, but when I try and add the marker, nothing happens, nor to I receive any error in Chrome.

As a POST addition I've added the Geocode JS File below:

var geocoder;
var map;
var marker;

// initialise the google maps objects, and add listeners
function gmaps_init(){

  // center of the universe
  var latlng = new google.maps.LatLng(54.312195845815246, -4.45948481875007);

  var options = {
     zoom: 6,
    center: latlng, 
    scrollwheel: true,     
    draggable: true, 
    mapTypeId: google.maps.MapTypeId.SATELLITE
  };

  // create our map object
  map = new google.maps.Map(document.getElementById("gmaps-canvas"), options);

  // the geocoder object allows us to do latlng lookup based on address
  geocoder = new google.maps.Geocoder();

  // the marker shows us the position of the latest address
  marker = new google.maps.Marker({
    map: map,
    draggable: true
  });

  // event triggered when marker is dragged and dropped
  google.maps.event.addListener(marker, 'dragend', function() {
    geocode_lookup( 'latLng', marker.getPosition() );
    var point = marker.getPosition();
    map.panTo(point);
    document.getElementById('osgb36lat').value = marker.position.lat();
    document.getElementById('osgb36lon').value = marker.position.lng();
  });

  // event triggered when map is clicked
  google.maps.event.addListener(map, 'click', function(event) {
    marker.setPosition(event.latLng)
    geocode_lookup( 'latLng', event.latLng  );
document.getElementById('osgb36lat').value = marker.position.lat();
  document.getElementById('osgb36lon').value = marker.position.lng();
  });
}

// move the marker to a new position, and center the map on it
function update_map( geometry ) {
  map.fitBounds( geometry.viewport )
  marker.setPosition( geometry.location )
  document.getElementById('osgb36lat').value = marker.position.lat();
  document.getElementById('osgb36lon').value = marker.position.lng();

}

// fill in the UI elements with new position data
function update_ui( address, latLng ) {
  $('#gmaps-input-address').autocomplete("close");
  $('#gmaps-input-address').val(address);
  $('#gmaps-output-latitude').html(latLng.lat());
  $('#gmaps-output-longitude').html(latLng.lng());
}

// Query the Google geocode object
//
// type: 'address' for search by address
//       'latLng'  for search by latLng (reverse lookup)
//
// value: search query
//
// update: should we update the map (center map and position marker)?
function geocode_lookup( type, value, update ) {
  // default value: update = false
  update = typeof update !== 'undefined' ? update : false;

  request = {};
  request[type] = value;

  geocoder.geocode(request, function(results, status) {
    $('#gmaps-error').html('');
    if (status == google.maps.GeocoderStatus.OK) {
      // Google geocoding has succeeded!
      if (results[0]) {
        // Always update the UI elements with new location data
        update_ui( results[0].formatted_address,
                   results[0].geometry.location )
 document.getElementById('osgb36lat').value = marker.position.lat();
  document.getElementById('osgb36lon').value = marker.position.lng();
        // Only update the map (position marker and center map) if requested
        if( update ) { update_map( results[0].geometry ) }
      } else {
        // Geocoder status ok but no results!?
        $('#gmaps-error').html("Sorry, something went wrong. Try again!");
      }
    } else {
      // Google Geocoding has failed. Two common reasons:
      //   * Address not recognised (e.g. search for 'zxxzcxczxcx')
      //   * Location doesn't map to address (e.g. click in middle of Atlantic)

      if( type == 'address' ) {
        // User has typed in an address which we can't geocode to a location
        $('#gmaps-error').html("Sorry! We couldn't find " + value + ". Try a different search term, or click the map." );
      } else {
        // User has clicked or dragged marker to somewhere that Google can't do a reverse lookup for
        // In this case we display a warning, clear the address box, but fill in LatLng
        $('#gmaps-error').html("Woah... that's pretty remote! You're going to have to manually enter a place name." );
        update_ui('', value)
      }
    };
  });
};

// initialise the jqueryUI autocomplete element
function autocomplete_init() {
  $("#gmaps-input-address").autocomplete({

    // source is the list of input options shown in the autocomplete dropdown.
    // see documentation: http://jqueryui.com/demos/autocomplete/
    source: function(request,response) {

      // the geocode method takes an address or LatLng to search for
      // and a callback function which should process the results into
      // a format accepted by jqueryUI autocomplete
      geocoder.geocode( {'address': request.term }, function(results, status) {
        response($.map(results, function(item) {
          return {
            label: item.formatted_address, // appears in dropdown box
            value: item.formatted_address, // inserted into input element when selected
            geocode: item                  // all geocode data: used in select callback event
          }
        }));
      })
    },

    // event triggered when drop-down option selected
    select: function(event,ui){
      update_ui(  ui.item.value, ui.item.geocode.geometry.location )
      update_map( ui.item.geocode.geometry )
    }
  });

  // triggered when user presses a key in the address box
  $("#gmaps-input-address").bind('keydown', function(event) {
    if(event.keyCode == 13) {
      geocode_lookup( 'address', $('#gmaps-input-address').val(), true );

      // ensures dropdown disappears when enter is pressed
      $('#gmaps-input-address').autocomplete("disable")
    } else {
      // re-enable if previously disabled above
      $('#gmaps-input-address').autocomplete("enable")
    }
  });
}; // autocomplete_init

$(document).ready(function() { 
  if( $('#gmaps-canvas').length  ) {
    gmaps_init();
    autocomplete_init();
  }; 
});

I've been working on this for some time and I just can't seem to work out where I'm going wrong.

I would be very grateful and I wondered whether it would be possible that someone could take a look at this and let me know where I'm going wrong.

Many thanks and kind regards

IRHM
  • 1,326
  • 11
  • 77
  • 130
  • That code is probably fine (my visual debugger isn't as good as running it in a browser) so I guess the issue is how it's added into your existing working page. Does "nothing happens" mean that even the geocoding part stops working, for example? – Andrew Leach Jun 05 '12 at 13:59
  • Hi @AndrewLeach, thank you for taking the time to reply to my post. The map and the geocode function work fine, and in isolation the loading of the marker works without any problems. However, when I put them together only the geocode works. I've added my `geocode` code to my original post if it helps. Kind regards – IRHM Jun 05 '12 at 14:06
  • When it fails, what response do you get back from the google with the geocode request? Does your geocode have the correct data you expect? If you wrote this code then you know how to plot a marker. The difficult part will be getting your geocode to work correctly, so isolate that. – steampowered Jun 05 '12 at 14:48
  • Hi @steampowered, thank you for looking at and replying to my post. As I said initially the problem I'm having isn't associated with the `geocode` request, that element is working fine. The problem I have is that I cannot load the existing marker from the MySQL database. I hope this helps. Kind regards – IRHM Jun 05 '12 at 15:06
  • Hi, did you notice that your php is returning errors in inclusion? –  Jun 05 '12 at 15:41

2 Answers2

0

As per my comment, your PHP code is returning errors:

<b>Warning</b>:  include(admin/link.php) [<a href='function.include'>function.include</a>]: failed to open stream: No such file or directory in <b>/homepages/2/d333603417/htdocs/development/test.php</b> on line <b>44</b><br />
<br />
<b>Warning</b>:  include() [<a href='function.include'>function.include</a>]: Failed opening 'admin/link.php' for inclusion (include_path='.:/usr/lib/php5') in <b>/homepages/2/d333603417/htdocs/development/test.php</b> on line <b>44</b><br />
<br />
<b>Warning</b>:  include(admin/opendb.php) [<a href='function.include'>function.include</a>]: failed to open stream: No such file or directory in <b>/homepages/2/d333603417/htdocs/development/test.php</b> on line <b>45</b><br />
<br />
<b>Warning</b>:  include() [<a href='function.include'>function.include</a>]: Failed opening 'admin/opendb.php' for inclusion (include_path='.:/usr/lib/php5') in <b>/homepages/2/d333603417/htdocs/development/test.php</b> on line <b>45</b><br />
<br />
<b>Warning</b>:  mysql_query() [<a href='function.mysql-query'>function.mysql-query</a>]: Can't connect to local MySQL server through socket '/tmp/mysqld.sock' (2) in <b>/homepages/2/d333603417/htdocs/development/test.php</b> on line <b>47</b><br />
<br />
<b>Warning</b>:  mysql_query() [<a href='function.mysql-query'>function.mysql-query</a>]: A link to the server could not be established in <b>/homepages/2/d333603417/htdocs/development/test.php</b> on line <b>47</b><br />
<br />
<b>Warning</b>:  mysql_fetch_array(): supplied argument is not a valid MySQL result resource in <b>/homepages/2/d333603417/htdocs/development/test.php</b> on line <b>48</b><br />
<br />
<b>Warning</b>:  mysql_close(): supplied argument is not a valid MySQL-Link resource in <b>/homepages/2/d333603417/htdocs/development/test.php</b> on line <b>54</b><br />

This is why you can't get data from MySQL.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
  • Hi @Jorge Ferreira, firstly, thank you for spending time to get back to me and secondly, my apologies for the error you're getting. I think I've fixed the problem. I had incorrectly left the links used in my live site in the file. I've now removed these. Once again my apologies. Kind regards – IRHM Jun 05 '12 at 16:03
  • Okay, so for what i understand the problem is in the SQL, right? where does $lid come from? –  Jun 05 '12 at 19:08
  • Hi @Jorge Ferreira, thank you for getting back to me with this. I don't think that the issue is with SQL, I think it is because I'm trying to do two things on one map, i.e. load an existing marker, whilst also including `reverse geocode` functionality. With respect to `$lid` and also `$idnum`, these are variables which make sure that the correct records are retrieved for the current user. Many thanks and kind regards – IRHM Jun 06 '12 at 10:44
0

After considerable time spent searching the web and re-writing existing code, I've found the solution to my problem.

The loading of markers and geocode functionality came from this site. With some time re-writing this to suit my needs, I've been able to create a page with the desired functionality. Kind regards

IRHM
  • 1,326
  • 11
  • 77
  • 130