Jump to content

Map Marker Map


ryan

Recommended Posts

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.
  • Like 4
Link to comment
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

Link to comment
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.

Link to comment
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.

Link to comment
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.

Link to comment
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?

Link to comment
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.

Link to comment
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 :)

Link to comment
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.

Link to comment
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

Link to comment
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. :)

  • Like 1
Link to comment
Share on other sites

  • 1 month later...

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.

Link to comment
Share on other sites

  • 2 months later...

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

Link to comment
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>
  • Like 2
Link to comment
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

Link to comment
Share on other sites

  • 1 month later...

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.

  • Like 3
Link to comment
Share on other sites

  • 4 months later...

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,

  • Like 2
Link to comment
Share on other sites

  • 4 weeks later...

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'));
});
});
  • Like 1
Link to comment
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.

  • Like 6
Link to comment
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
×
×
  • Create New...