jQuery Store Locator Plugin
I can’t believe it’s been over a year since I first published my Google Maps store locator JavaScript code. I’ve had several requests for an updated version and that post has definitely received more traffic than any of my others. I’ve finally created a new version of the locator using Google Maps API version 3 and this time I’ve turned it into a full-on jQuery plugin. I re-worked almost everything in the code but I don’t think I’m going to go through function by function like I did in the last post. jQuery should make this store locator much easier to implement and I’ve included several options. Without further ado, here is the full documentation for the plugin:
jQuery Google Maps Store Locator Plugin
Files can be downloaded from GitHub and will be in the /dist directory
This jQuery plugin takes advantage of Google Maps API version 3 to create an easy to implement store locator. No back-end programming is required, you just need to feed it KML, XML, or JSON data with all the location information. How you create the data file is up to you. I originally created this for a company that didn’t have many locations, so I just used a static XML file. You will need to geocode your locations beforehand or use a geocoding API service if you want to try to do it on the fly. The reason for this is that all free geocoding APIs have strict limits that would easily be exceeded. In the end, you’re much better off storing the coordinates versus having to look them up for each location on each request.
A note on the distance calculation: this plugin currently uses a distance function that I found on the blog of Chris Pietschmann. Google Maps API version 3 does include a distance calculation service (Google Distance Matrix API) but I decided not to use it because of the current request limits, which seem somewhat low. For v2 I also tried experimenting with the Directions API to request distances but also found the limits to be too restrictive. So, the distance calculation is “as the crow flies” instead of a road distance calculation. However, if you use the inline directions option that does provide the distance that’s returned via the directions request.
Last, it’s very important to note that the plugin requires the Handlebars template engine. This separates the markup of the infowindows and location list elements so that they can easily be restructured. Handlebars pretty slick, will read Mustache templates, and the built-in helpers really come in handy. Depending on what your data source is, 2 of the 4 total templates will be used (KML vs XML or JSON) and there are options to set the paths of each template if you don’t want them in the default location. If you’re developing something for mobile devices the templates can be pre-compiled for even faster loading.
Options
It is much easier to maintain the current list of options on GitHub vs. a gigantic HTML table, which is why I’m now including the options.md file in the repository. If you need to view options for a previous version please view the old options page.
Usage:
Assuming you already have your locations.xml file set up in the current directory and the basic HTML copied from the example index file, the following would be the simplest usage example:
1. Include the css file (you’ll most likely want to make modifications to this beforehand):
<link rel="stylesheet" type="text/css" href="assets/css/storelocator.css">
2. Include jQuery if you don’t have it on your page already (the example below uses the Media Temple CDN but you can load it from wherever you’d like):
<script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>
3. Include the latest version of Handlebars.js (this is now required)
<script src="assets/js/libs/handlebars.min.js"></script>
4. Create a new Google Maps API key and make sure to enable Google Places API Web Service, Google Maps Geocoding API and Google Maps Directions API for the project in the Google API Console after setting up the initial Maps key.
5. Include Google Maps API with your key. If you want to target a particular country add “®ion=” to the end of the URL followed by the country code.
<script src="https://maps.google.com/maps/api/js?key=yourkey"></script>
Region targeting example:
<script src="https://maps.google.com/maps/api/js?key=yourkey®ion=UK"></script>
6. Include the plugin file:
<script src="assets/js/plugins/storeLocator/jquery.storelocator.js"></script>
7. Apply the storeLocator plugin to the map-container div.
<script> $(function() { $('#bh-sl-map-container').storeLocator(); }); </script>
8. Make sure you have the basic form and map container HTML set up or copied from the example file.
Geocoding:
To geocode all your locations you can use a free or paid service or use the geocode.html that I included. This provides a basic form and will use the Google Maps API to give you the latitude and longitude of the location you input.
JSON (optional):
I’ve added JSON support as an option with version 1.2 of the plugin, which is completely optional. The JSON file included in the GitHub repository is just there as an example. The file was generated via PHP from a MySQL database. The database structure I used for the example is pictured in the following image:
Outputting the JSON from the database is extremely simple with PHP. Make the database connection with MySQLi and use something such as:
$results = $db->query("SELECT * FROM locations"); $locations = array(); foreach($results as $location){ array_push($locations, $location); } //Output JSON echo json_encode($locations);
Then you’d just set the dataLocation setting in the plugin directly to the PHP file and the dataType setting to json.
Support:
I’ll try to answer basic questions and create more examples but my time is limited.
- Demo example
- Modal window example
- Default location example
- HTML5 auto geocode example
- KML example
- JSON example
- Maximum distance example
- No form tags example
- Bootstrap (responsive) example
- Category filtering example
- Custom category markers example
- Inline directions example
- Name search example
- Pagination example
- Raw data example
- Query string example
- XML format example for location data
Tutorials
- Using the jQuery Store Locator with thousands of locations
- Using query string parameters with the jQuery Store Locator
Cardinal Store Locator
Donations
Some people have asked to donate. Feel no obligation but if you want to my Paypal email is bjorn2404@gmail.com and I also have a Bitcoin address set up: 17ueYyfaxCyEXedecVnr3w7GjM9PJD4CHj
Special thanks
My initial motivation for creating this jQuery plugin was a custom implementation request of my older JavaScript locator for Phin & Phebes Ice Cream. If you’re on the east coast be sure to seek out a pint.
Oops! We could not locate your form.
Is it possible to have the input form on 1 page and the results & map on another? If so what’s the easiest way to do it? I’m not that great with vars and string etc so not sure how i’d go about achieving this
Hi Dex,
Is there any reason you need to have it display on a new page? It could be done but since we’re using jQuery I’d recommend at least using a modal window to display the results instead of taking the user to a new page.
Hello Bjorn,
I have a great need to display the results on their own page, as it would better stick to the current site layout I am using it in.
Thanks in advance!
I’ve been working on this, and ended up figuring out a fix to push the results to another page. I basicly make my own form on the first page, which is identical to the form used to get the customers zip. I use a php post variable to catch the zip on the next page, which I then echo into the hidden address field. After which I run a jquery timer to autosubmit the zip, giving the affect that the map is being loaded on the 2nd page. If people are interested in this, I’ll post some source.
Thanks!
Hi Christopher,
Can you please post it?
Thanks in advance
On the first page you have the below:
Enter Address or Zip Code:
Which will get a $_POST value of address, and pass it along to locations_map.php
Now on locations_map.php you have the following
The timer/auto-submit
$(‘document’).ready(function() {
setTimeout(function() {
$(“#submit”).trigger(‘click’);
}, 2);
$(‘#submit’).click(function() {
$(‘#user-location’).submit();
});
and the hidden form
<input type="hidden" id="address" name="address" value="”/>
And wala! You have a results posted to another page!
can i see this in action?
Hi Christopher
i tried your code and i get and error
can you please help me out with the two pages
Thanks
Hi there, well done for the nice work, I wonder if this would be possible without the map? I currently have mysql table with locations in UK postcode, all I need to do is have user search their postcode and return the nearest 5 results with a weblink to each result. We never want users to know where or how far the location is?
Any advice much appreciated?
Hi there, please ignore above comment have sorted that bit now. I have tried to use your demo in FF, Chrome & IE, all works fine except IE, it displays the map in right div but not the list of places in left div? I have tried using Edina on your demo site with no success?
Is this not compatible with IE?
Many thanks
Hi Gary, I thought it was working the same in all browsers but I am seeing the same thing that you are. I’ve been meaning to switch the .live() on line 74 to the new .on() http://blog.jquery.com/2011/11/03/jquery-1-7-released/
.live() should still work but it has been deprecated in jQuery 1.7+. I’m not sure if that will fix it at the moment but you could try that until I get time to work on in this weekend.
Hey Gary – oops, I left a couple of console.logs in my last commit (one on line 206 and the other on line 208), which seem to be causing the issues in IE. If you remove those it should be fine. I’ll be committing a new version to GitHub momentarily.
Hi first great script I have been looking for some thing along thse lines….ok simila question to Dex about displaying in another way you mentiona modal window I understand what this is but not the principal about adding this any enlightment on how I can achieve this thanks
Hello SimpleUser, I’m working on adding a modal window option to this plugin. I’m hoping to have it ready tomorrow, or within the next couple of days.
Fantastic news Bjorn 🙂 not being the best coder myself I played around with this with some jQuery modal code but I couldnt get it to work once again thanks for this.
I’ve just pushed the latest version to GitHub, which includes the modal window option. I also created a modal window example. Be sure you’re using jQuery v1.7+ or it won’t work.
Tnanks Bjorn this is much appreciated. 🙂
Hi Bjorn, that’s great thanks, fixed the ie9 issue.
Kind regards and great work.
Good morning Bjorn, just another quick thing I noticed, if I add a value to the search field to offer information it allows the script to return results based on no search?
In my customised form on search field I have
If the user simply hits enter or search button its returns random results each time. I am working my way to fix this [maybe!] with my very limited knowledge but thought I would share in case you hadnt come across it..
regards
Gary
Ahh wont let me submit my code above input class=”searchfield” type=”text” value=”Enter Postcode…” onfocus=”if (this.value == ‘Enter Postcode…’) {this.value = ”;}” onblur=”if (this.value == ”) {this.value = ‘Enter Postcode…’;}” id=”address” name=”address”
Hi Gary, I think I understand what you are saying. I agree that it should stop processing if the input is blank. It will show an alert if the box is blank but it continues to process. I just pushed a new version to GitHub that fixes that. It was basically just missing the else on line 93 – I may have even had it in there at one point and removed it for testing or something.
Thanks again Bjorn, much appreciated, my testing doesn’t appeared to have fixed that issue on my site, perhaps its just mine?
My search field has a text value of “Enter PostCode”, when a user clicks in this is removed and the search begins.. If the user doesn’t click the input field and just hits search it returns values , not sure what they are based on if there is no postcode entered?
Its not a great problem, I can remove the text or reply on my visitors being sensible!!
Kind regards
Gary
Hi again Bjorn, excuse the avalanche of questions!
Are you aware if this could be changed to take the location feed from JSON instead of xml? I only ask because I have a scenario whereby locations need to remove themselves from the search dynamically.
With JSON I would have the location check a box which sets them as ‘unavailable’, this then omits them from any search until they re-check in.
As you probably can tell I am no developer but I dont think I can manage the xml via php/mysql so thought JSON woudl be my only method?
Kind regards
Hi Gary,
You could change it so that it used JSON instead of XML pretty easily. $.ajax can handle both data types: http://api.jquery.com/jQuery.ajax/
You’d then have to change how the variables are collected in the code right below that.
However, you can definitely output XML with PHP.
– PHP4 Example: http://www.tonymarston.co.uk/php-mysql/domxml.html
– PHP5 Example: http://www.tonymarston.co.uk/php-mysql/dom.html
On the clear on focus, try using some jQuery instead. Not sure if this is going to format very well but I use this for accomplishing that (change the ID to your input ID):
if($(‘#inputID’).length)
{
$(‘#inputID’).focus(function() {
if ($(this).val() === ‘Enter PostCode’) {
$(this).val(”);
}
}).blur(function() {
if ($(this).val() === ”) {
$(this).val(‘Enter PostCode’);
}
});
}
hi bhorn thanks for the great plug in. but i have a problem here. whenever i try to search anything it shows all the results instead of showing the nearest one. Can you please help me resolve this issue thanks.
Hi Dipen,
If you want to change the amount of locations returned just use the storeLimit option. If you only want to show 1, then in step 5 above you’d use this instead:
$(function() {
$(‘#map-container’).storeLocator({‘storeLimit’ : 1});
});
Hi, great plug-in – one of the best I’ve seen! 🙂
Quick question; is there a way to delay the plug-in from loading until the xml file has been downloaded fully? This would allow us to have more stores listed (we have around 1000 locations)?
Hi Paulo,
I guess you could try using the async setting with the ajax request – adding async:false, after line 120. That may hang up the browser a bit though.
The plugin should be pretty quick by default but I haven’t tried it with that many locations. You may want to try both ways.
Hi again Bjorn, thanks for the responses to my json query. Been trying to fathom this out for ages now with no success due to my lack of understanding, nothing to do with your excellent script. Would I need to change the jquery.storelocator.js file, editing ‘xmlLocation’ : ‘locations.xml’, to ‘xmlLocation’ : ‘locations.json.php’? Then create locations.json.php to pull the rquired fields into it? As long as I call the columns in the table the same as your xml should it work ok?
Sorry for long winded response, using json would really help to remove locations that were offline, I could simply get teh usesr to update their status in php?
Kind regards
Gary
Hello,
I was wondering a few things. Is it possible to not have the map generate after an input, but instead have the map always display with a default location?
Also, how can I set the default map to the terrain setting?
Thanks,
Walt
Silly me. I didn’t realize there was a mapType setting. So, I made the map terrain by default.
But, I’m still wondering the first thing I asked about.
Thanks,
Walt
Hey Bjorn, good the website is working again.
So I basically had the same question Walt has.
Was wondering how to show the map by default and not just after submitting an address.
Tnx allot for this fine piece of code.
Ok, one at a time – I’ll get back to the others later this evening.
@Gary: Yes, you’d want to update the location to path of the PHP file that outputs the JSON. This setting is a URL. Assuming it’s a local file you should be fine using a relative path. You’ll also need to switch the dataType on line 123 from xml to json, line 124 and 129 change xml to json, then just after 129 is what you’ll really need to focus on. I don’t think jQuery’s find is going to work so you’ll need to replace it with something like this (it depends on how the JSON is structured):
$.each(json.location, function() {
var name = this.name;
var lat = this.lat;
var lng = this.lng;
.
.
.
locationset[i] = new Array (distance, name, lat, lng, address, address2, city, state, postal, phone, web, hours1, hours2, hours3);
i++;
});
So, keep the variables the same but change the way they are gathered. Then make sure to create the locationset array at the bottom and include the i++. I didn’t test that syntax but I think it’s right. Once you get the variables set correctly the rest should work without needing any changes. See the following page on the jQuery site for more info on the ajax call with jQuery: http://api.jquery.com/jQuery.ajax/ and the following page on jQuery’s each iterator: http://api.jquery.com/jQuery.each/
Walt and Lau, do you want to still include the input box and allow people to search? If you want to keep that, all you would need to do would be comment out line 43 and run the mapping function with your default latitude and longitude. Maybe I’ll add this as an option to the plugin. For example, put this after line 44:
mapping(44.991565, -93.216323);
Bjorn, I posted a question and then implemented your fix named here and I was able to get the entire view of the US. I would like to have no markers display initially on load until the user enters their data, but have a list of the locations alphabetically… is this possible? Right now it is using the default location named in the mapping lat/long…
Thanks!
I know this stuff is *super* old, but it’s still the best plugin of it’s type. I’m also trying to get a map to show with a default location before the user does a search. I think referring to the line numbers in the javascript file makes this a little difficult, since I’m sure those line numbers change over time. Has anyone ever figured out how to get this to work?
Bjorn,
Thanks. Excellent plugin; easy to implement, even for someone without much knowledge of jQuery.
Walt
Hello Bjorn,
To begin: really great plugin, thanks!
I have just one question. Is there a way to tell the plugin to display stores not based on a limit as set in:
$(
Hey John, I think the script is getting cut out to prevent spam. Are you talking about the 26 location limit?
One of the finest map codes i have ever see. Just wanted to say thanks you and nice one.
Yes. I want it to be based on radius instead of a plain 26 location limit. So for example, the sidebar will show all the locations within a 60 mile radius. Thanks, John
hi bjorn,
i’ve used your plugin on my clients website bananwax.com.au however once i input more than 10 stores in the locations.xml file it won’t work…is there something i’ve done wrong or forgetting to change?
i’m not a programmer as such so don’t have any knowledge of jquery or javascript, just basic html/css.
thanks in advance
Hi Dylan,
Did you check to make sure the XML is valid? XML is very touchy – if there is one syntax error it will break. Try running your XML through the validator on the W3C site with your 11th location: http://validator.w3.org/
This is a great script. Thanks for publishing. Question – can it utilize the ability for the browser to detect location? Perhaps by geo-IP address?
hi bjorn,
i thought that could of been the problem, however i inherited the site from another designer who thought it was a good idea to build in tables, so i’m scared to put it through the validator!
i will try though and let you know how i go, hopefully i don’t need to re-build the site from the ground up!
i’ll keep you posted…thanks!
hi bjorn,
i ran the XML through the validator and got this:
Missing “charset” attribute for “text/xml” document.
The HTTP Content-Type header (text/xml) sent by your web browser (Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:12.0) Gecko/20100101 Firefox/12.0) did not contain a “charset” parameter, but the Content-Type was one of the XML text/* sub-types.
The relevant specification (RFC 3023) specifies a strong default of “us-ascii” for such documents so we will use this value regardless of any encoding you may have indicated elsewhere.
Warning No DOCTYPE found! Checking XML syntax only.
The DOCTYPE Declaration was not recognized or is missing. This probably means that the Formal Public Identifier contains a spelling error, or that the Declaration is not using correct syntax, or that your XML document is not using a DOCTYPE Declaration.
Validation of the document has been skipped, and a simple check of the well-formedness of the XML syntax has been performed instead.
it still only works if I only input 10 stores. not sure if it matters but i am using australian addresses/locations? any ideas? thanks
Hello everybody, and thank you Bjorn for this EXCELLENT jquery storelocator! I tried to implement a new feature to my project: geolocalize the user in order to automatically display all the nearest stores from him. I succeded to localizate the user, and to return his coordinates (“position.coords.latitude” and “position.coords.longitude”). How can I make them automatically display the map with the markers? Hope it’ll be working soon 😉
Hi Bjorn, Thanks for the awesome plugin and recent upgrade to V3 compatibility. I have been impressed with your JQuery approach since V2 but remain unable to add 2 way marker sidebar listeners. ESA 2009 was able to establish this type of two-way focus link between the sidebar entry and the marker right after Google Maps API V3 was released, and I would like to devise a way to add this to your solution with or without JQuery. If not familiar with the bidirectional binding, please see the Finland example here: http://koti.mbnet.fi/ojalesa/boundsbox/makemarker_sidebar.htm
That sample code has been up since 2009 but there have been few (if any) successful emulating implementions that have been able to duplicate that stellar bidirectional binding functionality between the marker and the corresponding sidebar entry. I also am having trouble porting his elegant javascript functions to your solution.
The Finland approach uses prototypes in the SidebarItem() and makeMarker() functions to establish two-way binding between the sidebar entry and the marker so that when the marker is clicked the sidebar entry is highlighted (and vice versa). When you click the sidebar the map pans and infowindow opens (like with yours), but in that version there is an extra piece, which I crave. When you click a marker, the corresponding sidebar item is also identified (this part does not happen in yours). Can you help me/us figure out how to integrate this excellent Finland (ESA 2009) functionality to your approach? SidebarItem() and makeMarker() are public domain functions but they have been difficult for newbies like me to integrate. Any online or offline advice would be appreciated.
Thanks again for the fine JQuery plugin!
-JO
@Dylan: Can you post your XML data with more than 10 location on http://pastebin.com
@youyouk: Comment out line 43 and run the mapping function with the coordinates – you could put it after line 44. Ex: mapping(44.991565, -93.216323);
@JO: I’ll see if I can get the 2 way listeners working. I’ll probably experiment a bit this weekend.
hi bjorn,
here is the XML – http://pastebin.com/2BiJJ36s
thanks for your help, much appreciated!
Hi Dylan,
It looks like it’s the ampersand in Cnr Marine Parade & Dutton Street. Use:
instead of just &. You can find a full list of special characters and the corresponding codes here: http://www.webmonkey.com/2010/02/special_characters/
Hi Bjorn, good job!
Can i use the plugin without lat and lng??only with city and adress?
thanks
Hi Mike,
There is a geocoding function in this plugin but it currently only geocodes the user’s location. If you know JavaScript, you could make some modifications to use the function starting on line 62. The user location geocoding call begins on line 95. You could copy what’s there down to where the XML data is collected after line 144, format the address, do the geocoding and then use the latitude and longitude it returns for the distance calculation and the locationset array. I chose not to do it this way to keep things quick and to avoid any geocoding errors but I may add it as an option in the future.
it is possible to have a code ex because i’m not good in js
Thanks
Hi Bjorn, just a quick one to say a big thank you for all your help with the plugin and helping get it working perfectly on my site. Really is a great plugin from a great developer.
Kind regards
Gary
HI Bjorn, I posed the bidirectional binding question for mutual event handling on StackOverflow: http://stackoverflow.com/questions/10591816/binding-google-map-markers-to-non-map-sidebar-entries and cited your excellent plug in. @Beetroot-Beetroot came up with a suggestion, and that strategy might be relevant for future enhancements of your jQuery Plugin. Thanks for this excellent tool.
-JO
Hi Bjorn, thank you for such an amazing plugin! Exactly what I was looking for.
I have a small issue. I have kept all the default settings except brought down the store limit to 5. The plugin works great and all my store locations load fine, but when map is initially loaded with results, it’s a bit offset from the first location and the user has to either click on the first result or scroll around to find the location on the map. Any idea what could be causing this? A little issue, but one that my client may complain about.
Hi Romina,
By default the map center’s on the user’s location. If a zip code is entered that can cover a large area. I would try changing the zoomLevel setting out to 11 or 10:
Works great, thanks!
hi bjorn,
using ‘&’ instead of ‘&’ fixed it! thanks so much! can’t believe I missed that!
all your help was much appreciated!
sorry just one more thing,
when i enter an australian postcode, the map shows somehwere in hungary,
is there a way around this? no big deal but the client would like users to be able to search with postcode as well…
thanks
Can you give me an example of a postal code that causes an error? If you go to Google Maps and put in the zip code does it return the correct location?
Hi Bjorn,
Many thanks for this fantastic plugin !
I experienced the same problem as Dylan with Belgian zipcodes, i simply added an address manual to the xml file, it worked fine when i enter the cityname but not when entering the zipcode.
I solved this by changing, in the index.html file :
to the google domain of the default country (.be in my case)
Greetings
hi bjorn,
when i enter 4220 on google maps it shows me the correct location.
Hi just want to say get plugin but I’m having difficulty changing the markers from letters to just plain markers with the black dot
just wondering if you could give me a example of what to do and i’m sorry but I’m new to jquery so learning as I go along also just wondering if I could use more then one XML file for store lists.
Thanks in advance
Rob
Hello Robert,
If you replace line 242 (map = …) with the following it will use the regular Google Map points.
I’m not sure if you could use multiple XML files. I’d recommend combining them.
Hi again Bjorn, is it possible within the js file to remove the hyperlink from any information on results to just the web link? For example on your demo http://www.chipotle.com would be a link [pionter cursor] but the info above [Chipotle Edina
6801 York Avenue South
Edina, MN 55435
952-926-6651] wouldn’t be a link to anywhere, currently it moves the map to its pointer but I am using without a map at present?
Thanks
Hi again Gary,
If you look inside the “listClick” function you can replace it with the following:
Also, you’ll want to remove the “cursor: pointer;” in the stylesheet – line 91, so it doesn’t look like you can click on the list elements.
Quick question, how do I go about having the driving directions open up in a new window when clicked on. Or, have them open up in a modular window.
Thanks!
I would just like to say a massive thank you for releasing this awesome piece of code for free. The only thing missing here is a “donate” button!
I have now built a bit of PHP which queries my database to build the XML file on the fly. Couple of points for anyone else trying to do this …
1) The XML needs ALL the fields whether you use them or not.
2) If you want to have other inputs within the form that gets submitted for example to exclude/include things from the query which creates the XML then you will need to change this line var userinput = $(‘#’ + settings.formID).serialize(); to something like var userinput = $(‘#address’).serialize(); in the javascript otherwise it will serilaize all the elements in the form and not work.
Thanks again for the excellent code!
Good point on the serialize. I’ll change it to the input ID in the next update.
Excellent work! Thank you for sharing!
I was hoping that you could assist in answering two questions, if possible –
1. How can the distance calculation be displayed in the markers list?
2. How can I easily take an HTML table (outputted from a Salesforce.com database via Siteforce) -> JSON -> Plugin (instead of the XML)
Thank you in advance
Tottaly awsome.
I too would be interested in displaying the distance from, as above.
One other question, can we set the zoom of the displayed map dynamicaly to include the nearest 5 or 10 locations?
So even if the search results are a long way away, and we center to the search location, we still see some markers and the zoom adjusts accordinly?
Cheers,
TW
Distance has has been added to the location list in version 1.2. You’re second request sounds like it could be somewhat challenging – I’m not sure if I want to focus on adding that at the moment over the other potential additions.
Hey Bjorn,
Thanks for this amazing plugin.
One question, is it possible to let the Search field accept letters such as
Hi Jeppe,
It looks like your comment got cut off. You should be able to use any characters that you can with Google Maps.
Hey Bjorn, when I try to use letters like
It seems like my comment gets cut off everytime I use the letters im talking about. But when i use these letters I get the error “Geocode was not successful for the following reason: ZERO_RESULTS”
Can you paste what you’re trying to do at Pastebin?
Hey Bjorn,
Thanks for taking your time to help out, much appreciated.
I wrote my problem over at pastebin at http://pastebin.com/QDE6QyMW
Thanks in advance
Hello Bjorn,
In addition to my previous question; I thought of creating a “view all shops” page where it loads my xml file and list all 55 of the stores in the #list as I listed them in the xml file (i listed them alphabetically).
I want to do this because I have very limited space to work with on the site that I’m working with now, and right now my main shop locator page shows a maximum of 4 shops near the entered location, because I don’t want the horizontal scroll (my store list is horizontal instead of vertical like on your example).
I don’t have that much knowledge of jquery/javascript so I thought maybe you could help me out editing the jquery.storelocator.js to show all of the shops without the need of the form, and save that as another javascript file, and just load that file on allshops.html.
Thanks in advance.
Best regards,
Jeppe
Hello, I’ve a new question: is it possible to make all the marker automatically appears when the map is loading?
Thank you 🙂
Hi,
I’m not sure what you mean. Can you clarify the question at all?
Hi!
The idea was to automatically show the stores around a predefined point on the map, before the user make his search.
For example, I succeded to show on the map the position of the user when he’s loading the StoreLocator page, and I would like the plugin automatically show markers around these coordinates.
Actually the plugin only react AFTER the submit of the “formID”. Is there a way to send it the “user-position” on first loading?
(my jQuery skills are as limited than my english, sorry ^^)
Best regards
HTML5 has location detection built in and I’m planning on adding that as an option very soon. However, not all browsers support this. In addition, the user has to agree to let the browser determine their location. It would be great for mobile users.
Hi Bjorn,
Thanks for that great Plugin.
I am trying to implement it to search in Spain, but it does not work. I cannot manage to set up a marker in locations and read it accurately. The list does not include that new marker I write in the xml file, and google maps does not locates it in Spain.
Thanks very much for your help.
OSCAR
Hi Oscar,
Try what Bart mentioned about – replace the maps.google.com in the HTML file with your countries domain extension: maps.google.es
Hi Bjorn,
I solved the above issue.
It was a problem of cache. I firstly checked your xml locations file, so when I try to add or change other locations Firefox cache avoid the plugin to recognise new ones (I guess). At least, that is the way I solved it.
Thanks again for your great code.
OSCAR
Is there a way to include driving directions with this plugin?
To those I haven’t responded to yet. Distance and JSON will be easy and I’m going to include them in the next release (hopefully this weekend). I’ll also try to get the driving directions in but that might take a little longer.
Fantastic news – anxiously awaiting the distance enhancement!
Hi Bjorn, I’m trying to incorporate your plugin into my webpage but I’m having trouble. I’ve copy and pasted your code in and uploaded the xml file just to see if I can get it to work. My page displays everything up to the entry form (where it says Enter Address or ZIP) just fine, but when I actually enter in a ZIP code and hit enter the page refreshes and neither the maps nor the locations show up.
To give you some background, I have at most a basic understanding of HTML and CSS, and I’m currently using Dreamweaver to make my site. I used the built in FTP uploader to upload both the index.html file you provided and the xml file. Any help would be appreciated, thanks in advance
I believe the problem lies with how I uploaded the xml file. Is there a special way I need to do that? I simply uploaded it alongside the html file, is there a particular way it needs to be linked to the file?
Did you upload the JavaScript files? Or is there an example I can see somewhere?
Hi Bjorn, thanks for the quick response. I was able to get the plugin to work myself (the simplest of errors…I fixed it by using the absolute URL when I included the plugin). I actually had another question for you in regards to the XML locations file. I can’t seem to add or remove any locations. I copy and pasted the last location to see if I could add one more, and I even tried deleting all the markers, but the store locator kept showing the original 20 locations. Any help would be appreciated, thanks in advance.
Are you definitely loading your XML file? I’d also try disabling your browser’s cache while you work on it if you know you have the file path correct. The jQuery ajax call will cache the data by default. You can override that with the cache setting: http://api.jquery.com/jQuery.ajax/
If you’re using Firefox, get the web developer toolbar plugin – under the disable menu you can disable the cache. I’m sure there’s probably a way to do it with the Chrome developer tools as well.
I think you have a problem with the jquery.storelocator.min.js file located on your github. I had to view the source of your online demo and copy and paste that file in order to get it working.
For those not getting it to work, download and use this file:
http://bjornblog.com/storelocator/js/jquery.storelocator.min.js
I pushed version 1.2 to GitHub this morning, which includes optional JSON compatibility, a default location option, and the distances to each location in the left location list. I haven’t had a chance to update the documentation above yet but I should be able to get to it tonight.
Alright, the documentation above is updated and there are now examples of setting a default location and using JSON instead of XML. I’m hoping to add some other things soon: driving directions, HTML5 location detection and possibly mustache templates for the infowindows and location list.
I honestly can’t wait for:
– Driving directions
– HTML5 location detection
Bjorn, you are my hero!
Hi,
Totaly understand.
Distance is great.
I had some limited sucsess with Map.”bounds”
Declare it:
var bounds = new google.maps.LatLngBounds();
Then for each marker, extend thebounds object:
bounds.extend(myLatLng);
Then display the bounds:
map.fitBounds(bounds);
But it didnt totaly work.
Worked Ok, unlses the results were out of range, then went haywire.
I was working on displaying a green marker for the location of the search request.
Then having the locations displayed (thank you)
Then using bounds to display the nearest markers, so even if its miles away, the user can still see how far the nearest is.
I may have another go later, if i get some time
Thanks,
Hey,
Nice plugin, just one question. How can I use data from a JSON object received on post (ajax post)?
Is it difficult to make this geolocate and automatically show the nearest store, without entering a post code or address?
OR maybe give the option of “Find me” next to the address input box?
hi bjorn,
great work with the plugin!
i was wondering is there a way to allow users to search using state & postcode?
for example:
i live in Victoria, Australia
i would like to have a form field with the list of states in australia, and second field where they can enter their postcode, the user is then presented with the list of stores in that state and those closest to their postcode.
many thanks in advance 🙂
cheerio,
S.
Great plugin, is there a donation button we can send some funds to?
With Default location can we show all stores in the USA?
This would be perfect for our application.
like
http://www.papayaclothing.com/shop/store_locator_v1.php?code=loc&m=
hi bjorn,
with in the XML there is a type – example :type=”Outlet”
can that be incorporated into the search an option or dropdown?
thanks
-alan
Hi,
it is the best store locator ever.. 🙂
Can You help me? Where I can to change the REGION code?
Becouse if I’m typing a zip code, the map shows a wrong Country.
Thanks
Botor from Hungary
Hi botor,
Change:
to:
Dear Bjorn:)
Thanks but we have an other serious problem:(
In my country have more town that name has ő,
Just pushed v1.3 to Github, which adds direction links and an HTML5 geolocation option. I’ll circle back and get to some of the unanswered questions the next couple of days.
Whenever I try the “HTML5 auto geocode example” from either your demo pages or uploaded to our test server we get the error message: ” Automatic location detection failed. Please fill in your address or zip code. ” – What gives?
…ok, it didn’t work the first 10 times I tried but now – without changing anything – it’s working.
…but another computer in the same office (and on the same wifi network connection) still does not work and gives the error.
I don’t know if I’d recommend using the automatic gelocation on a locator that is going to be used primarily by desktop users. It’s not supported by IE less than 9 and it seems to be faster in some browsers than others. For example, Chrome seems must quicker at this than Firefox. It’s also not always accurate. I can look into it a bit more to see if there are ways to make it better but I’d say that the HTML5 geolocation API functionality is kind of so-so at the moment. I’d definitely recommend it for mobile users over desktop users.
I had the same problem. This may be because after repeated testing attempts, Chrome thinks that the webpage is trying to spam your browser with auto location attempts, so the error appears.
*FIX*
If you click the automatic detection icon in chrome (cross-hair icon on right side next to the bookmark star) you can clear the settings and it should go away.
You can also just disable the error from displaying if you must:
function autoGeocode_error(error)
{
//If automatic detection doesn’t work show an error
//alert(settings.autoGeocodeErrorAlert); /*Comment out this line*/
}
Dear Bjorn:)
Thanks but we have an other serious problem:(
In my country have more town that name has ő
sorry I would like write a comment but the system is not ready….
Dear Bjorn:)
Thanks but we have an other serious problem:(
In my country have more town that name has accented characters..
example the name of town ”Kecskem
sorry I would like write a comment but the system is not ready….
Dear Bjorn:)
Thanks but we have an other serious problem:(
In my country have more town that name has accented characters..
example the name of town ”Kecskeme’t” if i write the name”Kecskeme’t” i get a system message ”Geocode was not successful for the following reason: ZERO_RESULTS”
But if i write ”Kecskemet” (with non unicode character) the script is working correctly.
But in my country the users will write: Kecskeme’t, Pe’cs, Gyo”r, etc…
Can I fix or Can You fix that serious problem?
Big Thanks
Hi Botor,
Try putting the following after line 70. Let me know if it works and I’ll include it as a patch.
Hello,
I’ve had this problem for months now and still can’t figure out how to solve this issue.
I tried your suggestion, but it didn’t solve it either.
I’d love to hear if Botor made it work.
I just pushed v1.3.1 to github, which should fix this issue. Please let me know if it works for you.
Hello Bjorn,
I downloaded v1.3.1 and now I’m getting the error “Geocode was not successful for the following reason: INVALID_REQUEST” when I enter the exact same search text as I did before. I’m searching for the danish city Elsinore (it’s spelled differently in danish, with a special character oe).
Quote from https://developers.google.com/maps/documentation/javascript/geocoding : “google.maps.GeocoderStatus.INVALID_REQUEST generally indicates that the query (address or latLng) is missing.”
Thanks.
Ok, it’s something to do with the character encoding. This is a tough one but I’m working on it. I thought it would be fixed in this version because I was getting umlauts to work but I’m also having it fail with that character.
Ok, I really appreciate your help.
I hope it’s not as difficult as it sounds and I really hope you will make it work :).
Thanks a lot.
PS. I still get errors with umlauts as well, I just tested J
Jeppe, I just pushed v1.3.2 up to GitHub. I removed the extra encoding line I added and all the special characters I try now in addresses seem to work.
Hmm for me it still doesn’t work. It’s not because I’m testing it locally right?
I get the ZERO_RESULTS error again.
Hi,
I have use the store locator and its looking great.
But they really want to display all locations on a map prior to a search.
I guess it wouldnt need to display the list on the left and the pins could be without letters prior to a search.
Is there a simple way to do this.
Any thourghts?
Thanks,
TW
just set you perameters differnt if the input box is empty i.e. first load
if (($(“input#address”).val())!=”” )
{
storenum =19;
}
I also changed the zoom.
//if no text in the text box then set zoom to 11
if (($(“input#address”).val())==”” ) {
var myOptions = {
zoom: settings.zoomLevel,
center: new google.maps.LatLng(orig_lat, orig_lng),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
} else {
var myOptions = {
zoom: 11,
center: new google.maps.LatLng(orig_lat, orig_lng),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
}
Hi Bjorn,
Your script is FANTASTIC – thanks. Is there a way to make the starting Pin image/icon different than the rest? I used a custom marker for my locations and don’t want the same one for the starting location.
Thanks
Hi Bjorn,
tnx 4 ur great job !
i have just a couple of questions …
A. how can i change the distance calculation unit from miles to km ?
B. could i have two different zoom level ? i mean opening the default-location-example.html
the default point at zoom 6 and after the address search query at zoom 12.
tnx
A. solved 🙂
How did you change the distance calc from miles to km? I’m also trying to do the same thing.
Hi Luke,
This should be pretty easy. There’s a variable on line 58 called GeoCodeCalc.EarthRadiusInKilometers. You can swap out the Miles one with this one on line 234 and 262. Also, the term miles is used in the output in a couple of places: 281 and 384/385.
I’ll make it a setting in the next version but that should work for now.
I am having a problem that is difficult to explain. It really has nothing to do with your awesome store locator, but more in how it is interacting with other elements on my page. I have a footer element that is usually about 200 px but on the store locator page it is more like 550 px. I have taken away all of the code one at a time it seems that the map-container div is causing an issue. You can see it in action at: http://retailsitecommon.afstores.com/Develop/FreshMarket/locations.html
Any help would be greatly appreciated because this is an awesome store locator and I would love to use it!
Hi Bjorn,
tnx 4 ur great job !
On the basis of your script, I have created a storelocator(http://glenindia.com/storelocator).
Its working perfect , but in some cases(like: state- Haryana & City- Faridabad) it’s doesn’t show any result. XML(http://glenindia.com/storelocator/locations.xml) generated, but result not appears.
Map doesn’t appear in some cases, but xml generated.
Plz advice.
Thanks in advance.
Hi Bj
Ah, a mistake occured! I was saying it was a great ideai to add the Diections features in the last update! Is there any way to add a category filter, with custom markers apllied to them? It could be very usefull 🙂
Thank ou for your nice plugin and your support, you rock!
Hello and thank you for all the hard work!
I am currently trying to implement your system, and although I do have it all working correctly
(in modal mode), I would like to push the map and results to another page…Would this be possible with the current codebase?
Thanks in advance for any and all help 🙂
I’ll do an example within the next couple of days.
Hi Bjorn,
Do you know how to push the map and results on a seperate page?
For example:
Page A diplays the form with submit button
Page B shows the results including map.
Modal window just isn’t what we need.
Bjorn, this is absolutely AMAZING! Thanks so much! A quick question: Is there an easy way to restrict the results shown by distance? Say you had a drop down box that a user could choose to see the closest locations within a maximum distance of 10 miles, 20 miles, 50 miles 75 miles. Can you then feed that info to the plugin? Thanks again!!!
Or if there was a way to only show locations that were X miles away by default, that would work just as good. 🙂 Currently some of the locations are close, but it also shows some that are 5-600 miles away because there aren’t that many in the search location, so it would be good to eliminate the farther ones if it’s possible? Thanks again!
Never mind I figured it out. 🙂 I just added a simple if statement around line 234:
//Only show locations that are less than 100 miles away
if(distance<100){
//Create the array
locationset[i] = new Array (distance, name, lat, lng, address, address2, City, State, ZipCode, PhoneNumber, web);
i++;
}
Hi David, this is exactly what I’m trying to implement. Can you give me the exact location that I can past your if statement? I’m in no way a js programmer, but I can follow instructions pretty well, usually :). Thanks for your help.
One more thing… I’m using the xml file instead of json. I’m not sure, but it might change where I put that location limiter statement. Thanks!
changing dataLocation to be a PHP file is not working !!!
also, can I set the dataLocation to URL ?!
Thanks for the great plugin 😉
I was able to get data location to work by setting it to a PHP file. Using the following (in the dealer locator page):
$(function() {
$(‘#map-container’).storeLocator({‘jsonData’: true, ‘dataLocation’: ‘WriteJson2.php’});
});
Where WriteJson2.php was my PHP file and it was in the same folder as the dealer locator page. Try testing your PHP page by itself to ensure it’s outputting correctly, then take the output and run it through a JSON validator.
One last question. I added a checkbox to the form (to show authorized dealers only. Is there an easy way to check if a checkbox on the form was checked and then either A. call a different PHP file that outputs JSON than the default one, by using an if statement in the function call below (e.g. if checked, call JsonAuthorized.php else call: JsonNormal.php).
$(function() {
$(
(oops the system cut if off the rest of the question)
One last question. I added a checkbox to the form (to show authorized dealers only. Is there an easy way to check if a checkbox on the form was checked and then either A. call a different PHP file that outputs JSON than the default one, by using an if statement in the function where the dataLocation is set (e.g. so if checked, dataLocation: JsonAuthorized.php else dataLocation: JsonNormal.php).
Or B. Pass that info to the PHP file that outputs the JSON? The query is working correctly on the Json php file, I just am having trouble passing the variable to the JSON page. I tried setting the form to call itself and then catch the $_POST superglobal, but the JSON php page doesn’t seem to be receiving the variable that was set. Thanks so much for your time!
Yes, you can do A pretty easily with jQuery. If you put something like the following before the $.ajax({ it should work.
Hi, this is great, thanks!
Would this be easy to integrate with a wordpress site?
I tried copying the html code into a wordpress page, and copying the folder to the wordpress directory, changing the paths in the index.html…
But it’s just dawning on me that it’s not quite as simple. Anyone know a simple hack?
How familiar with WordPress skinning are you? I’d copy the JS and CSS files into the theme directory and use wp_enqueue_script and wp_enqueue_style in the theme’s functions.php file – that’s the proper way to include these files. You don’t need to include jQuery because WordPress already includes that by default.
So, you’d include the map stylesheet, the Google Maps API script, the plugin script and create a new template file with the Map div and put the code in step 5 in the template file or a separate custom scripts file for your theme.
Dont have much knowledge with JSON but wondering how to approach accessing places/adresses from a saved map within google and feeding this as the locations to this plugin..
It looks as if this is the right direction https://www.bjornblog.com/web/jquery-store-locator-plugin#comment-2327
But not sure where to start. Here is my saved map with all locations. https://maps.google.com/maps/ms?msa=0&msid=212167611152658744851.0004b334c118366207b10
Any step in the right direction would be appreciated, I wan’t to figure this out, just dont know where to start 🙁
You can export Google My Maps data to KML, which currently isn’t supported with the plugin but it would make a lot of sense to add it. I’ll add that to the list for the next version.
If you need it fast you could convert the KML data to regular XML without too much work. If you view the source on the “XML format example for location data” link above that’s the format the XML should be in.
Any example template on how to use this in a responsive design layout? Where it automatically adjusts to any screen size whether on desktops, tablets, and mobiles.. I wish to setup the results at bottom for smartphones then when used on tablets the results end up on sidebar..any tips would be helpful..
Hello, ou should try Twitter Bootstrap, it’s a good package to start a new responsive project 🙂
http://twitter.github.com/bootstrap/index.html
Hi,Thanks for having this site and for all the hard work. I used the html code part in an .aspx page with data from an .xml file it worked fine(in my local and on a server). Only downside is it takes too long to load the locations, so i’m trying to get .json to work. I’m using visual studio and it’s working fine on my local computer but when i push it to a hosting server it does not work. Please let me know the what might be causing this not to work on the server, and if you have any suggestions for it. Thanks in advance.
Hi, i’m sorry for my english.
I have a problem with the script. In safari everything work perfect but in firefox and in chrome dosn’t work. the problem occurs when I push the submit button and the map doesn’t appear.
I use the version with json data.
I tested the script with firebug but there isn’t errors.
Can you help me?
For more information there isn’t any problem with your on line example but if i try with the same your code downloaded the script doesn’t work and the map did’t show.
Do you have a link where I can see it?
I’m just getting started with your plugin but so far I think it’s exactly what I need. My client will likely be giving me location updates via Excel file, maybe around 200 locations total. Do you know a good way to go from an Excel file to an XML file formatted the way your plugin requires? Or, how difficult would it be to add CSV support?
You should be able to convert from CSV to XML (a quick google search revealed some converters). You could also import the CSV file to a database and output XML or JSON with a back-end programming language – either way.
I used the following method to export my Excel 2007 Spreadsheet into the same format as the locations.xml document:
1. Performed Step 1 of this link (to install the XML export add-on) – http://office.microsoft.com/en-au/excel-help/create-an-xml-data-file-and-xml-schema-file-from-worksheet-data-HA010263509.aspx
2. Performed Step 1 of this link (to display developer tab and get access to XML add-on) – http://office.microsoft.com/en-au/excel-help/export-xml-data-HP010206401.aspx#BM1
3. Lay out a worksheet with the following headings: name, lat, lng, category, address, address2, city, state, postal, country, phone, email, web, hours1, hours2, hours3, featured
I found that I needed to convert all columns to text, columns that were left blank needed a inserted so they still contained data and so that all fields would export properly in XML.
4. Click ‘Developer’ on the Office Ribbon and then click ‘Source’.
5. On the XML source flyout click ‘XML Maps…’.
6. Click ‘Add…’ and in the Select XML Source dialogue box, navigate to locations.xml. Click ‘Open’ and then ‘OK’.
7. You should now have a list of elements in the XML flyout, drag and drop the elements from the flyout to the matching column heading on the spreadsheet until all are matched. Let Excel match the data types if it prompts you.
8. Now go back to the ‘Developer’ ribbon, select ‘Export’, enter your desired filename in the ‘Export XML’ dialogue box and click ‘Export’. (I just used the locations.xml file name after renaming the demo file something else so I didn’t have to worry about changing the lookup name in the .js file)
9. Open up your new XML file in Notepad or similar and go to ‘Edit’ -> ‘Replace’.
In the ‘Find what’ box type: ” ”
In the ‘Replace with’ box type: “”
Click ‘Replace All’
10. Save the file and load the Store Finder demo and check to see if it works.
In step 3, instead of reading ‘… columns that were left blank needed a inserted so …’ it should say ‘… cells or columns that were left blank needed a space inserted so …’
Another quick question, if I don’t want the Geocoding to be automatic but instead I want to add a “find me” type of button to activate the function what is the correct way to do this? Currently, on a button I’m using:
onClick=” $(‘#map-container’).storeLocator({autoGeocode: true});”
It seems to work but I’m not sure it’s the correct or best way to implement a “use my current location” feature.
Any help would be greatly appreciated.
Thanks.
Yes, the autoGeocode option is the only way to get the user’s location automatically.
Hi Bjorn,
great tool indeed. Although I have question. I would like to use the storecollector in a page with an accordeon jquery. Think “two tabs”, one tab is wholesaler, second tab installers. And for some reason I cannot get both instances at work. I made a second instance of storelocator.js, of the cms, renamed all divs, made a second xml, but now way that the both work (seperate instances work fine, even with the changes). I’m not a programmer, but can read/understand code quite well. I think it’s a js or geocode conflict (something that cannot be loaded twice). I searched some jquery forums, but no result.
So, any advice on putting two instances on the same page :),
best regards
gys
Hello, I dont know why, but I can apply a new PinColor to the markers of the “listclick” (for example a green one when the contact is a client, and a blue one when it’s a prospect).
Unfortunately,I tried to apply it to the markers shown on the map, but in this case the colors are shift. The first got an “undefined” PinColor, and the second marker got the color of the first one, the third one the color of the second etc etc …
Here is my code :
_________________________________
var $storeType;
if (storeType == “CLIENT”) {
pinCouleur = ‘A5B478’;
}
else {
pinCouleur = ‘3A87BD’;
}
var pinImage = new google.maps.MarkerImage(”http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=” + letter + ”|” + pinCouleur + ”|” + settings.pinTextColor,
__________________________________
…
I made a screenshot, it will be easier to understand ^^
http://www.hostingpics.net/viewer.php?id=697953storeLocatorPinColor.jpg
http:// http://www.hostingpics.net/viewer.php?id=697953storeLocatorPinColor.jpg
Help would be appreciated 🙂
how do u fix it ?
Hi, I like this plug in… could you just tell me if there is a way of showing the location that you just search on the map with a different colour pointer so when I type a post code I want that to be a green pointer on the map where as all the stores/my locations are red pointers. If thats possible how do I go on about doing it?
Hello, check out here:
https://www.bjornblog.com/web/jquery-store-locator-plugin#comment-3253 😉
I’ve tried integrating this into a wordpress theme as well and cant seem to get the map to display. What is odd is that if I have a standard HTML file serv this page, the map works beautifully… Once I put it in my theme .php file the map wont display.
I’ve done some debugging and can see that the scripts are registering and appear to be working, but when I enter a zip code and submit, this registers in the :
But then nothing comes back from the maps API… Its like it sends the request, but never gets anything back.
Looks like my code snippets didnt go through…
I
Hey I love the plugin. But I’m having problems in Chrome especially. I have the plugin on a a jquery mobile page and when I enter a postal code and press submit, the map appears on the page for a minute then disappears.
https://staging.nvenergy.com/jq/locationsCopy.html
Hello, you should try to declare the storelocator javascript in the footer, AFTER the Google map script.
I’ve been trying to get this locator to work with roughly 80 locations. My problem is, it will work with 26 locations, however, as soon as I add more than this, it stops working. How can I fix this??
Is there possible to have an select list with geotags thats loads on map just like search?