ryan

Map Marker Map

443 posts in this topic

FieldtypeMapMarker Module for ProcessWire 2.1+



This Fieldtype for ProcessWire 2.1+ holds an address or location name, and automatically geocodes the address to latitude/longitude using Google Maps API.

This Fieldtype was also created to serve as an example of creating a custom Fieldtype and Inputfield that contains multiple pieces of data.

Download at: https://github.com/r...ldtypeMapMarker


How to Use


To use, install FieldtypeMapMarker like you would any other module (install instructions: http://processwire.c...wnload/modules/). Then create a new field that uses it. Add that field to a template and edit a page using that template. Enter an address, place or location of any sort into the 'Address' field and hit Save. For example, Google Maps will geocode any of these:


  • 125 E. Court Square, Decatur, GA 30030
  • Atlanta, GA
  • Disney World

The address will be converted into latitude/longitude coordinates when you save the page. The field will also show a map of the location once it has the coordinates.

On the front end, you can utilize this data for your own Google Maps (or anything else that you might need latitude/longitude for).

Lets assume that your field is called 'marker'. Here is how you would access the components of it from the API:
 

<?php
echo $page->marker->address;    // outputs the address you entered
echo $page->marker->lat;        // outputs the latitude
echo $page->marker->lng;        // outputs the longitude

Of course, this Fieldtype works without it's Inputfield too. To geocode an address from the API, all you need to do is set or change the 'address' component of your field, i.e.
 

<?php
$page->marker->address = 'Disney Land';
$page->save(); // lat/lng will now be updated to Disney Land's lat/lng

post-1-132614281154_thumb.png

Edited by Nico Knoll
Added the "module" tag.
4 people like this

Share this post


Link to post
Share on other sites

Thanks again for another useful module.

I've been testing this out and everything works as expected. Here is some initial feedback and a question.

- Is it possible to distribute modules like this with additional files (css, js etc) already in a folder? It might save some confusion and make the install simpler - i.e just copy this MapMarker folder into the modules directory and press the check for new modules in the admin interface.

- Add a link in readme.txt to this forum post (the instructions here seem more current)

- Add an explanation of the status codes (OK Approximate, OK Rooftop etc) or maybe just a link to the google maps info on responses :

http://code.google.com/apis/maps/documentation/javascript/services.html#GeocodingResponses

- After saving a location, set the default zoom of map to be a bit closer (like 15)

- It would be nice to update the map without pressing save (just being picky now :)

- Will this module eventually replace or merge with the GMap Fieldtype module? The major functionality difference which I need, is being able to manually add a place on the map. I am using this for a Places directory and most of the locations cannot be geocoded or don’t have an actual address (parks, playgrounds, statues, points of interest etc.), so manually adding a point on the map is quite important.

Thanks,

Michael

Share this post


Link to post
Share on other sites

- Is it possible to distribute modules like this with additional files (css, js etc) already in a folder? It might save some confusion and make the install simpler - i.e just copy this MapMarker folder into the modules directory and press the check for new modules in the admin interface.

Just will comment on this. I don't get what you mean. It actually IS in a folder. THe download is like "ryancramerdesign-FieldtypeMapMarker-09847d5" just rename it to "FieldtypeMapMarker", drop it in modules folder and your set.

Share this post


Link to post
Share on other sites

Hi Soma - good point, thats a much simpler solution. I always get confused by the huge folder names that are auto generated by Github downloads

Share this post


Link to post
Share on other sites

Thanks for your feedback Mjmurphy!

- Is it possible to distribute modules like this with additional files (css, js etc) already in a folder? It might save some confusion and make the install simpler - i.e just copy this MapMarker folder into the modules directory and press the check for new modules in the admin interface.

I don't think I have control over the filename that GitHub creates for the ZIP file. So what Soma suggested to rename it is probably the best bet. Or, this would be even better if you have the capability on your server:

cd site/modules/ 
git clone git://github.com/ryancramerdesign/FieldtypeMapMarker.git

Then you'll end up with a nice dir called /site/modules/FieldtypeMapMarker/ with all the files in it. :) And whenever you want to update it, just do this:

git pull

…and that's all there is to it.

- Add a link in readme.txt to this forum post (the instructions here seem more current)

Good idea, I just did it.

- Add an explanation of the status codes (OK Approximate, OK Rooftop etc) or maybe just a link to the google maps info on responses

- After saving a location, set the default zoom of map to be a bit closer (like 15)

I'm actually planning on doing something with the combination of these two. I'm going to use the status codes to determine the zoom level. Just haven't gotten around to it yet. But zoom level is one of those things that is a bit hard to predict what people will need. For instance, I needed it zoomed out in the project where I used it. I figured the safest bet is to zoom according to the address accuracy and/or provide a config option that lets people set what default zoom they want.

- It would be nice to update the map without pressing save (just being picky now

I agree it would be nice. :) But this is a Fieldtype that's designed to function non-interactively (like if you were using it from the API), so the geocoding can't be dependent upon javascript. If interactive updates were added, they would have to be something separate (and perhaps something to do in a future version).

- Will this module eventually replace or merge with the GMap Fieldtype module? The major functionality difference which I need, is being able to manually add a place on the map. I am using this for a Places directory and most of the locations cannot be geocoded or don’t have an actual address (parks, playgrounds, statues, points of interest etc.), so manually adding a point on the map is quite important.

I wasn't thinking of it as a replacement for that module, though perhaps the functionality of the two could be combined. The primary intention with this module was to serve as a demonstration for people that are making their own fieldtypes. So I'm interested in keeping it straightforward and easy for someone to follow. If there's a way we can add the capability you've mentioned without adding much complexity to it, I'd certainly like to. I don't currently know how to add that capability, but am interested in learning how.

Share this post


Link to post
Share on other sites

@Ryan Thank you for another great module.

In the light of recent introduction of multilanguage features at least in dev branch I wanted to ask how can I make the map desplay in the language current back-end user is using? I tried to modify (hardcode) Gogle Maps API string, adding language parameter, but nothing changed.

EDIT: Oh, sorry. I found I can change it in init(), the only thing to do now is to "map" language code in PW with language code used in Google API. I wonder what is the best way to do it.

Share this post


Link to post
Share on other sites

Can you post what you found with how to localize Google Maps? I've not looked into this yet, and just wanted to have a starting point. I'll update the module to support PW 2.2 languages.

Share this post


Link to post
Share on other sites

It's as simple as use language=xx parameter in url, for now I just did this to request it in Russian:

$this->config->scripts->add(($this->config->https ? 'https' : 'http') . '://maps.google.com/maps/api/js?language=ru&sensor=false');

Language codes can be found here along with other information: Supported languages

So, I think, it's pretty easy to integrate maps localization in PW both into front- and back-ends. Just find a way to relate languages' codes with internal language names. Maybe it's a good idea to take this Google's language codes as a basis for PW's translations classification?

Share this post


Link to post
Share on other sites

Thanks for this info and link–that's a great reference. It looks like the language codes generally line up with the codes we're recommending people use for their language names (at least for the first 2 characters), but I don't think we can count on that.

I think what we'll do is have this module's installer add a field to the 'language' template (when present) that lets one specify the Google Maps language code for each language. Then this module can just get the language code from $user->language->gmap_lang; or something like that.

Share this post


Link to post
Share on other sites

Cool idea! I can't express enogh how much I love flexibility of processwire. The hardest task though is to make good decisions when your possibilities almost limitless and a system doesn't dictate you ways of thinking. Got to think yourself instead, a lot :)

I guess making such a flexible yet robust system is a extremely  challenging task, especially for just one brain. Tell us, Ryan, how did you invision PW back in the beginning of it's history, does it have any precursors which inspired its creation?

Sorry for offtopic, again :)

Share this post


Link to post
Share on other sites

Slkwrm, thanks for your kind words, glad you are enjoying ProcessWire. With regard to flexibility, I would just say that I prefer to let the project dictate the best way for things to go together rather than the platform. I think that comes from being a bit old school about design/development and not wanting CMSs interrupting the design/development workflow. I've written a few CMSs already over the last 10 years, several custom platforms and a couple previous products (Dictator and ProcessWire 1), so I guess I've had plenty of time to make mistakes, learn from them, and hopefully ProcessWire benefits from that. :) But don't give me too much credit, because it's mostly just trial and error, and time.

Give credit to yourself and the community here– ProcessWire is far better as a result of the community. Everyone here is helping to make it a much better and more flexible product than I ever could have on my own.

Share this post


Link to post
Share on other sites

The community is great indeed. I hope together we'll enhance and polish PW so it could shine brighter :)

Share this post


Link to post
Share on other sites
I would just say that I prefer to let the project dictate the best way for things to go together rather than the platform

That's why it's so funny that you named the CMS Dictator before :D

Share this post


Link to post
Share on other sites

Yes Dictator was a bad name. :) But it had good intentions. It was the name of one of Thomas Edison's inventions for some machine that assisted with outputting content. It was supposed to be that kind of Dictator, not the kind that tells others what to do or an evil ruler or anything like that. :)

1 person likes this

Share this post


Link to post
Share on other sites

I don't think I have control over the filename that GitHub creates for the ZIP file. So what Soma suggested to rename it is probably the best bet. Or, this would be even better if you have the capability on your server:

Ryan, you can easily create a release for download by adding a tag to a particular commit (git tag "tag_name"). This tag can be a version number (for example "pw2.3"). Then you can push your local tags to Github (git push --tags). It will automatically create a download file with a tag name + .zip extension. Look at this:

https://github.com/c...hp/cakephp/tags

That's how it works.

Share this post


Link to post
Share on other sites

Thanks for the tip Robert. I'd read about these tags, but never really understood exactly how they worked. Good to get some insight on this and perhaps I should start using them here.

Share this post


Link to post
Share on other sites

This module could be useful on my website about Sweden.

What I actually want is the following:

A zoomable Sweden map (Google Maps) with attractions, sight-seeing tips, national parks etc. These markers should be clickable and lead to a page about this specific attraction/sight-seeing tip etc.

Would this work with this module?

The easy part is to add the map marker field type to the pages. But how difficult is it to show the markers on the map and make it clickable? Is there someone here that has done something similar?

/Jasper

Share this post


Link to post
Share on other sites

If I'm understanding the need correctly, it's not that hard to do with Google Maps v3 API. Here's a few examples that uses the MapMarker fieldtype:

http://www.di.net/almanac/firms/

http://www.di.net/almanac/buildings/tallest-buildings/

http://www.di.net/almanac/buildings/art-museums/

These use the stock Map Marker fieldtype, so that each item (firm, building, art museum, etc.) has a Map Marker fieldtype. Then the index page with the big map cycles through all the children and adds the coordinates for each:

$js = "<script type='text/javascript'>RCDMap.init('map', 0, 0);";

foreach($page->children as $item) {
   $js .= "\nRCDMap.addMarker('{$item->title}', '{$item->url}', '{$item->map->lat}', {$item->map->lng});";
}

$js .= "</script>";
echo $js; 

The above uses my RCDMap class. Feel free to grab it if you find it helpful. You'll want to view the source on any of those URLs above to see how it works. http://www.di.net/almanac/site/templates/scripts/RCDMap.js

Note that you'll also need jQuery and Google Maps in your <head>:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
2 people like this

Share this post


Link to post
Share on other sites

Thanks Ryan, this was the kind of answer I was hoping for. :)

For some reason I started reading about FusionTables to store locations but that did seem way to complicated. :lol:

Now off to the building part....

/Jasper

Share this post


Link to post
Share on other sites

Since allow_url_fopen() is deactivated by some hosting companies here is a little workaround for using Curl:

open MapMarker.php and insert somewhere (e.g. after the last function) the following function:

private function file_get_contents_curl($url) {
 $ch = curl_init();
 curl_setopt($ch, CURLOPT_HEADER, 0);
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
 curl_setopt($ch, CURLOPT_URL, $url);
 $data = curl_exec($ch);
 curl_close($ch);
 return $data;
}

comment out the follwing check:

 if(!ini_get('allow_url_fopen')) {
  $this->error("Geocode is not supported because 'allow_url_fopen' is disabled in PHP");
  return 0;
 }

and change this line:

$json = file_get_contents($url);

to

$json = $this->file_get_contents_curl($url);

works fine for me.

3 people like this

Share this post


Link to post
Share on other sites

I just like to add work code, if some one have a problem to make it work, after install the Module.

This code is for parent page when the city map or address will show all children inside map,

echo "\n\n<div id='map1'></div>"; //div to show in template map

$js = "<script type='text/javascript'>";

$js .= "RCDMap.options.zoom = 2;";
$js .= "RCDMap.init('map1', 0, 0);";
foreach($page->children as $items) {
    $js .= "\nRCDMap.addMarker('{$items->title}', '{$items->url}', {$items->map->lat}, {$items->map->lng});";
}
$js .= "RCDMap.fitToMarkers();";

$js .= "</script>";
echo $js;

Here is code for a single page for city, hotels, or what ever u want to use it,

echo "<div id='map'></div>"; //div to show in template map

$js = "<script type='text/javascript'>";

$js .= "RCDMap.options.zoom = 10;";
$js .= "RCDMap.init('map', {$page->map->lat}, {$page->map->lng});";
$js .= "RCDMap.addMarker('{$page->title}', '', {$page->map->lat}, {$page->map->lng});";

$js .= "</script>";

echo $js;

CSS

#map {
width: 100%;
height: 300px;
margin: 1em 0;
}

#map1 {
width: 100%;
height: 500px;
margin: 1em 0;
}

JS

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>

<script type="text/javascript" src="http://www.di.net/almanac/site/templates/scripts/RCDMap.js"></script> /*this is from Ryan you can put it in your folder*/

Thanks to RYAN,

2 people like this

Share this post


Link to post
Share on other sites

Would it be possible to add drag and drop for pinning a location?

Like this: http://jsfiddle.net/salman/ZW9jP/4/

Got it working. Just the updating of the address filed when manually moving the marker is missing.

/**
* Display a Google Map and pinpoint a location for InputfieldMapMarker
*
*/

var InputfieldMapMarker = {

options: {
zoom: 5,
draggable: true,
center: null,
mapTypeId: google.maps.MapTypeId.HYBRID,
scrollwheel: false,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
},
scaleControl: false,

},

init: function(mapId, lat, lng) {
var options = InputfieldMapMarker.options;
options.center = new google.maps.LatLng(lat, lng);
options.zoom = 5;
var map = new google.maps.Map(document.getElementById(mapId), options);
var marker = new google.maps.Marker({
position: options.center,
map: map,
draggable: options.draggable
});
document.getElementById("_Inputfield_karta_lat").value = marker.getPosition().lat();
	document.getElementById("_Inputfield_karta_lng").value = marker.getPosition().lng();

	google.maps.event.addListener(marker, 'dragend', function (event) {
		document.getElementById("_Inputfield_karta_lat").value = this.getPosition().lat();
		document.getElementById("_Inputfield_karta_lng").value = this.getPosition().lng();
	});

}
};

$(document).ready(function() {
$(".InputfieldMapMarkerMap").each(function() {
var $t = $(this);
InputfieldMapMarker.init($t.attr('id'), $t.attr('data-lat'), $t.attr('data-lng'));
});
});
1 person likes this

Share this post


Link to post
Share on other sites

Thanks for your updates. This module has been updated with your changes, so it now supports drag-n-drop positioning.

While I was in there, I added reverse geocoding (generating an address from the marker position), live geocoding of the address changes (previously it required a submit) and a toggle checkbox to enable/disable geocoding.

6 people like this

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now

  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By bernhard
      Hi,
      just stumbled over a little module that i built for my last project. it helped me to test performance of my rockdatatables module to generate 3000 random json datasets and i want to share it with you. maybe it saves some time for someone.
      https://gitlab.com/baumrock/RockDummyData/
      easy example:
      $rdd = $modules->get('RockDummyData'); for($i=0; $i<15; $i++) { // this has to be inside the for-loop to always get a new dummy $dummy = $rdd->getDummy(); echo date("d.m.Y H:i:s", $dummy->timestamp) . "<br>"; } more advanced:
      $json = new stdClass(); $json->data = array(); $rdd = $modules->get('RockDummyData'); for($i=0; $i<3000; $i++) { // this has to be inside the for-loop to always get a new dummy $dummy = $rdd->getDummy(); $obj = new stdClass(); $obj->name = $dummy->forename . ' ' . $dummy->surname; $obj->position = $dummy->job; $obj->office = $dummy->city; $obj->color = $dummy->color; $obj->start_date = new stdClass(); $obj->start_date->display = date('d.m.Y',$dummy->timestamp); $obj->start_date->sort = $dummy->timestamp; $obj->salary = rand(0,10000); $json->data[] = $obj; } echo json_encode($json); you have to store your random datasets on your own into the /data folder. there are several services for creating all kinds of random data on the web - if you know one service that allows sharing those datasets let me know and i can include common needed data into the module
    • By AndySh
      Hello!
      I need your assistance please. I purchased the module FormBuilder. Unfortunately, the module discontinued delivering customer submissions to e-mail box specified in the module settings. Direct mailing to the e-mail box works OK. The module settings stays the same and are correct, like "Send e-mail to administrator(s) is checked. The last version of FormBuilder 3.0 has been installed. Please advise how to resolve the issue becase I cannot get orders from customers anymore (((
    • By kixe
      As described in this post (https://processwire.com/talk/topic/8551-custom-urls-for-pages/?p=82742) the option 'Name Format Children' under the tab 'Family' in template settings doesn't work properly and also not as expected. I had a look inside the code and made some changes which are working properly, which offers much more options, more consistency and less code too.

      The result is the following. You have 3 Options for generating name and title, which could be combined in endless variations.
      Name is always derived from title, same like creating pages manually.
      type date: if function detects # character anywhere in the string, conversion will be: deletion of # and string will be used as format parameter for PHP date() function type field: if string is a fieldname of the parent page the value of this field will be used type string: if string doesn't fit to the 2 preceeding it will be taken as it is All parts (separated by comma) will be composed in the order of setting. You can use unlimited numbers of parts

      I made a pull request on github: https://github.com/ryancramerdesign/ProcessWire/pull/831

      Example screenshots

      Setting ...


      will result in


       
    • By kongondo
      FieldtypeRuntimeMarkup and InputfieldRuntimeMarkup
       
      Modules Directory: http://modules.processwire.com/modules/fieldtype-runtime-markup/
      GitHub: https://github.com/kongondo/FieldtypeRuntimeMarkup
       
      This module allows for custom markup to be dynamically (PHP) generated and output within a page's edit screen (in Admin).
       
      The value for the fieldtype is generated at runtime. No data is saved in the database. The accompanying InputfieldRuntimeMarkup is only used to render/display the markup in the page edit screen.
       
      The field's value is accessible from the ProcessWire API in the frontend like any other field, i.e. it has access to $page and $pages.
       
      The module was commissioned/sponsored by @Valan. Although there's certainly other ways to achieve what this module does, it offers a dynamic and flexible alternative to generating your own markup in a page's edit screen whilst also allowing access to that markup in the frontend. Thanks Valan!
       
      Warning/Consideration
      Although access to ProcessWire's Fields' admin pages is only available to Superusers, this Fieldtype will evaluate and run the custom PHP Code entered and saved in the field's settings (Details tab). Utmost care should therefore be taken in making sure your code does not perform any CRUD operations!! (unless of course that's intentional) The value for this fieldtype is generated at runtime and thus no data is stored in the database. This means that you cannot directly query a RuntimeMarkup field from $pages->find(). Usage and API
       
      Backend
      Enter your custom PHP snippet in the Details tab of your field (it is RECOMMENDED though that you use wireRenderFile() instead. See example below). Your code can be as simple or as complicated as you want as long as in the end you return a value that is not an array or an object or anything other than a string/integer.
       
      FieldtypeRuntimeMarkup has access to $page (the current page being edited/viewed) and $pages. 
       
      A very simple example.
      return 'Hello'; Simple example.
      return $page->title; Simple example with markup.
      return '<h2>' . $page->title . '</h2>'; Another simple example with markup.
      $out = '<h1>hello '; $out .= $page->title; $out .= '</h1>'; return $out; A more advanced example.
      $p = $pages->get('/about-us/')->child('sort=random'); return '<p>' . $p->title . '</p>'; An even more complex example.
      $str =''; if($page->name == 'about-us') { $p = $page->children->last(); $str = "<h2><a href='{$p->url}'>{$p->title}</a></h2>"; } else { $str = "<h2><a href='{$page->url}'>{$page->title}</a></h2>"; } return $str; Rather than type your code directly in the Details tab of the field, it is highly recommended that you placed all your code in an external file and call that file using the core wireRenderFile() method. Taking this approach means you will be able to edit your code in your favourite text editor. It also means you will be able to type more text without having to scroll. Editing the file is also easier than editing the field. To use this approach, simply do:
      return wireRenderFile('name-of-file');// file will be in /site/templates/ If using ProcessWire 3.x, you will need to use namespace as follows:
      return ProcessWire\wireRenderFile('name-of-file'); How to access the value of RuntimeMarkup in the frontend (our field is called 'runtime_markup')
       
      Access the field on the current page (just like any other field)
      echo $page->runtime_markup; Access the field on another page
      echo $pages->get('/about-us/')->runtime_markup; Screenshots
       
      Backend
       

       

       
      Frontend