0

I've been researching how to add markers to a drupal 7 gmap for more hours than I feel comfortable admitting. The reason I have to do it through a module and not views is because of client specifications that I won't go into here. The code below is what I have so far, everything I've found seems to point in this direction and it looks right to me. But when I go to the page, no markers show on the map. Can anyone help me out here?

function rrs_custom_menu() {
$items = array();
$items['search-by-towns'] = array(
    'title' => 'Search by Towns',
    'page callback' => 'search_by_towns',
    'access arguments'  => array('access content'),
    'type'  => MENU_CALLBACK,
);

return $items;
}
function search_by_towns() {
$query = "SELECT node.title AS node_title, location.lid AS location_lid, location.latitude AS gmap_lat, location.longitude AS gmap_lon, location.name as loc_name, location.street, location.city, location.province, location.postal_code, gmap_taxonomy_node.marker AS gmap_node_marker, taxonomy_term_data.tid AS tid, taxonomy_term_data.vid AS vid, gmap_taxonomy_term.marker AS marker
    FROM 
    {node} node
    LEFT JOIN {location_instance} location_instance ON node.vid = location_instance.vid
    LEFT JOIN {location} location ON location_instance.lid = location.lid
    LEFT JOIN {gmap_taxonomy_node} gmap_taxonomy_node ON node.vid = gmap_taxonomy_node.vid
    INNER JOIN {taxonomy_index} taxonomy_index ON node.nid = taxonomy_index.nid
    INNER JOIN {taxonomy_term_data} taxonomy_term_data ON taxonomy_index.tid = taxonomy_term_data.tid
    LEFT JOIN {gmap_taxonomy_term} gmap_taxonomy_term ON taxonomy_term_data.tid = gmap_taxonomy_term.tid
    WHERE (( (node.status = '1') AND (node.type IN  ('listing', 'town')) AND (taxonomy_term_data.vid = '3') ))
    ORDER BY tid desc";


    $result = db_query($query);
    $marker = array();

    foreach ($result as $res) {
        $text = '<div class="location vcard"> <div class="adr"> <span class="fn">'.$res->loc_name.'</span> <div class="street-address"> '.$res->street.' </div> <span class="locality">'.$res->city.'</span>, <span class="region">'.$res->province.'</span> <span class="postal-code">'.$res->postal_code.'</span> </div> <div class="map-link"> <div class="location map-link">See map: <a href="http://maps.google.com?q='.$res->gmap_lat.'+'.$res->gmap_lon.'">Google Maps</a></div> </div> </div>';

        $marker[] = array(
            'latitude' => $res->gmap_lat,
            'longitude' => $res->gmap_lon,
            'markername' => $res->marker,
            'offset' => 0,
            'text' => $text,
            'opts' => array(
                'title' => '',
                'highlight' => 0,
                'highlightcolor' => '#FF0000'
            )
        );
    }

    $map_array = array(
        'id' => "auto1map",         // id attribute for the map
        'width' => "685px",        // map width in pixels or %
        'height' => "480px",      // map height in pixels
        'latitude' => '36.10237644873644',    // map center latitude
        'longitude' => '-80.8758544921875',  // map center longitude
        'zoom' => 8,              // zoom level
        'maptype' => "Map",       // baselayer type
        'controltype' => "Small"  // size of map controls
    );
    $map_array['markers'] = $marker;

  $output = theme('gmap', array(
      'element' => array(
        '#type' => 'gmap',
          '#gmap_settings' => $map_array,
          '#input'  => FALSE,
          '#theme'  => 'gmap',
          '#children'   => '',
          )
        )
    );

return $output; 
}

2 Answers 2

1

I wouldn't even get that fancy. Just use drupal_add_js to send an array of markers to a page, then call drupal_add_js to call your basic javascript that instantiates your map. Gmap hasn't been updated for V3 of the Google Maps API (so you need to go get a key, and you need to update the key when you move sites) and I've found that it's easiest, especially if you only need it on one page, to just call your own stuff.

EDIT: Maybe an example will help.

I had to do something similar where I wanted custom markers based on a set of results. In my preprocess I did:

  foreach($variables['results'] as $key => $result) {
    $store = node_load($result);
    $markers[$key] = array(
        'latitude' => $store->field_lat[0]['value'],
        'longtitude' => $store->field_lon[0]['value'],
        'title' => $store->title,
    );
  }
  $settings['markers'] = $markers;

  /* Add in the settings first */
  drupal_add_js($settings, 'setting');
  /* Then add in the javascript to instantiate map */
  drupal_add_js($module_path . '/map.js');

Then in my map.js:

Drupal.behaviors.map = function(context) {

  var initialZoom = true;
  mapInit();
};

function mapInit() {
  /* Get the markers variable set in PHP */
  var markers = Drupal.settings.markers;


  var myOptions = {
    mapTypeId : google.maps.MapTypeId.ROADMAP,
    scrollwheel : false,
    draggable : false,
    disableDefaultUI : true
  };
  var mapElement = document.getElementById("map");
  var map = new google.maps.Map(mapElement, myOptions);
  /* Loop through my markers and add them to the map */
  $.each(markers, function(index, value) {
    var latlng = new google.maps.LatLng(value.latitude, value.longtitude);
    bounds.extend(latlng);
    var marker = new google.maps.Marker({
      position : latlng,
      map : map,
      title : value.title
    });
  });
}
2
  • I've tried using drupal_add_js and the markers still don't show up. I've tried adding them to the footer, as a setting, etc. So when I saw the gmap api I went this direction, mainly because it makes the other maps on the site easier to deal with using views, but this one map is being a pain Commented Dec 9, 2011 at 13:46
  • I've added an example @Magicmarkker which I hope explains it a bit better.
    – Malks
    Commented Dec 10, 2011 at 0:11
0

Try using the jMapping jQuery plugin instead because it uses semantic markup to create a Google map. There are a ton of reasons to use this over gmap -- first and foremost you can leverage Google Maps JavaScript API V3. Also, jMapping has a callback that refreshes the map. This way you can have an event handler that listens for a change in zoom or map center location and use the lat / lng parameters to query the Drupal database that uses the super simple Ajax macro system in Drupal 7 to return the semantic data wrapped in a div element to the page which can trigger a jMapping refresh callback.

I didn't get that fancy because I'm going to first use Apache Solr to run the proximity search. I built a module that is hosted on Github that uses jMapping, it's a little dated because Geofield and Apache Solr Location for Drupal 7 hadn't been created yet which are now better than my system.

My implementation can be found on http://windwardguide.com if you want to see it in action. It uses Views of course

Here is the Views template for printing a row of information that contains the map information in the $metadata variable. Super easy to work with.

<?php
  $photo_count = trim(strip_tags($fields['field_photo_count']->content));
  $review_count = trim(strip_tags($fields['field_review_count']->content));

  $data = array();

  $data['lat'] = trim(strip_tags($row->field_data_field_address_field_address_lat));
  $data['lng'] = trim(strip_tags($row->field_data_field_address_field_address_lng));
  $data['path'] = trim(strip_tags($fields['path']->content));
  $data['nid'] = trim(strip_tags($row->nid));
  $metadata = array();
  if (!empty($data['nid']) || !empty($data['lng']) || !empty($data['lat'])){
    $metadata = array(
      'id' => $data['nid'],
      'point' => array(
        'lng' => $data['lng'],
        'lat' => $data['lat'],
      ),
    );
  $fields['metadata']->content = json_encode($metadata);
  }
?>


<?php if ($fields['metadata']->content): ?>
  <li id = "nid-<?php print $data['nid'] ?>" class="map-location" data-jmapping='<?php print $fields['metadata']->content ?>'>
    <a href="<?php print $data['path']?>" >
        <?php if (!empty($fields['field_logo']->content)): ?>
          <div class="map-logo"><div class="ml-level-1">
          <?php print $fields['field_logo']->content?>   
          </div></div>
        <?php endif; ?>
      <h3><?php print $fields['title']->content ?></h3>
      <div class="fivestar-rating">
        <span class="description">Average rating: </span>
        <?php print $fields['value']->content ?>
      </div>
      <div><?php if (isset($fields['proximity'])):?><?php print $fields['proximity']->content ?><?php endif;?></div>
      <div class = "reference-count">
       <span class = "photo-count">Photos (<?php print $photo_count ?>)</span>
       <span class = "review-count">Reviews (<?php print $review_count ?>)</span>
      </div>
    </a>
  </li>
<?php endif; ?>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.