Google Maps API - Marker, MySQL - php

I have read about Google's Geocoding Service which allows named locations (such as Manchester) to be mapped to coordinates from Google's DB so that markers can be placed on the Google Map: https://developers.google.com/maps/documentation/javascript/geocoding#Geocoding
In my circumstance I have a MySQL DB with a table jobs defined. In this table I store (unsurprisingly) job information, e.g. salary, job title, reference, etc. In this table is a column for the job location too. Most of the time it contains the city (or city plus postcode). The odd few times it is either NULL or has a string such as "No location specified".
To view these records I have a webserver running on my test machine and I display the records of the table in my browser with some HTML and general php script (a DB driven intranet page).
I have now split this page up into two sections. Using the Google Maps v3 API I have the bottom half containing the Google Map. What I am trying to achieve is:
automatic placing of markers based on the location strings in the
location column.
click-able markers where on-click they produce the
info window (which will contain job Title, etc).
What I want to know is what is the best way to do this?
I have read some similar posts here on SO where users have had a similar situation. From these readings I can ascertain that some OP's have made the effort to store the long/lat of the location of their record at the time it was inserted into the table and THEN read the long/lat with Javascript to produce the markers.
To do this I would need to modify some code and the table. This is one option, but I'd rather explore the other which is perhaps using Google's Geocoding service? Has anybody any experience with this? Any advice, recommendation you can give?
Also, lets say I used the latter option. I use PHP script to load the records from the DB. How would I pass the locations to Javascript so that the Google Map API can interrogate for long/lat with the Geocoding service? Is this a less optimal way of achieving it?
Thanks.

Just use Gmap3 Library, and you provide it an address...like so....
http://gmap3.net/en/catalog/18-data-types/address-63
You setup a div...
<div id="test" width=500 height=500></div>
Then your Jquery inserts the map into the div....
$("#test").gmap3({
marker:{
address: "Haltern am See, Weseler Str. 151"
},
map:{
options:{
zoom: 14
}
}
});
The address can be echoed from your PHP (this is considered bad practice though)
$("#test").gmap3({
marker:{
address: '<?php echo $addressfromDB;?>'
},
map:{
options:{
zoom: 14
}
}
});
But its better to do an ajax call, and then include this code in the success callback
$.getJSON('getlocation.php', function(data){
$("#test").gmap3({
marker:{
address: data.address // or whatever structure your json is in.
},
map:{
options:{
zoom: 14
}
}
});
});
That should get you started :)

It sounds like you have everything in place except for the Javascript and the way to get your data from the PHP script.
So lets start with getting the data from the PHP script in to the Javascript. The way to do this is using AJAX (for learning it, not an official source: http://www.w3schools.com/ajax/ajax_intro.asp). Once the web page has been loaded, Javascript can load more information by using an XMLHttpRequest object (or jQuery.ajax() if you prefer to use a Javascript framework). Basically this is Javascript loading a new page in the background and then doing stuff with the contents on it's own. You'll need to set up the PHP script (or make another one - I'm not familiar with this part) to provide the information that you want at a separate URI than the page you're visiting. Then you use this URI in the Javascript XMLHttpRequest. Typically you would get the PHP script to provide data in a form that's easy for computers to understand such as JSON (recomended) or XML (as apposed to HTML which is easy for human's to understand - once rendered). This procedure is called an API. In your JavaScript, you'll use JSON.parse() to turn the response text into actual variables that you can do stuff with.
Once you've got the addresses in Javascript, use the geocoding API you mentioned to turn them into GPS coordinates, and then the Google Maps Javascript API to place markers on the map: https://developers.google.com/maps/documentation/javascript/overlays#Markers. You can add an info window as well (search for InfoWindo in the above page - apparently I can only include 2 links).
As you've mentioned, it's probably a better idea to geocode all of the addresses and keep the lat/lon stored in the database. The biggest reason for this that if you geocode in Javascript as described above, then every time the user loads the page, geocoding will be re-done. This has two issues: 1. For Google, this is an expensive operation that costs them resources. 2. For you, this means it takes longer for the map to populate (because you have to wait on Google's response to your AJAX call - the geocoding one, not the one you'll be implementing as described above) and you might run into Google's usage limits which are in place because of 1. If you decide to geocode ahead of time and store the results in your database, you should be using "The Google Geocoding API", not the Javascript Geocoding Service. I can't add another link to it, but just Google "The Google Geocoding API".
I hope that helps, and if someone else wants to update my answer with more links, feel free.

Related

Real time tracking in google map

I already wrote a android apps to upload the lat and long to MySQL database(updated every 2min).
now, i have no idea how to show the real time location on Google map in the website(php,javascript,html)
which means how to dynamic update the Google map markers every 2 min [get the last two minutes records from MySQL database
and show the markers(update or disappear)]
and after i click the marker, it should show the info[get from mysql database(not important point because it same with static Google map!?]
just like this: http://traintimes.org.uk/map/tube/
I just know how to do when i just get 1 time (Static Google map!?) with my limited knowledge.
I have already searched same question in stack overflow and google
but i am sorry i still no idea how to do it because of my lack of knowledge.
Real time Google Map
anyone could give me some tutorial website or suggestion?
At last, thank all of you
and
I still a learner of English,I am sorry about any wrong grammar.
Real-time Tracking Geo Latitude/Longitude on a Map
You are looking to update coordinate entities (lat/lon position) on a map (google maps or otherwise) in real-time as the updates occur. Here is a blog post that may get you started in the right direction: http://blog.pubnub.com/streaming-geo-coordinates-from-mongodb-to-your-iphone-app-with-pubnub-using-websocket-sdk/ - this uses MongoDB and Ruby rather than PHP and MySQL. However it will be easy to get things setup in this case with a real-time map in PHP and MySQL on an HTML page with the following details. And there is a video too: https://vimeo.com/60716860
Using MySQL to Trigger Update in Real-time
First you'll want to use either MySQL triggers to push the Lat/Long coords - Invoke pusher when mysql has changed - this uses MySQL Triggers
Or as an alternative you may want to use PHP directly to invoke the push signal using a PHP push SDK as follows: https://github.com/pubnub/php#php-push-api
$pubnub->publish(array(
'channel' => 'live_map_coords',
'message' => array( 12.3482, 8.3344 )
));
Receiving The Push Message in JavaScript and Showing the Updates on a Map
<script src=//pubnub.a.ssl.fastly.net/pubnub-3.4.5.min.js></script>
<script>(function(){
PUBNUB.init({
subscribe_key : 'demo'
}).subscribe({
channel : 'live_map_coords',
callback : function(lat_lon) { alert(lat_lon) }
});
})();</script>
Once you have an map.html page with the above code in it, you can change the alert(lat_log) message popup with drawing coords on a map. Here is a fully working map drawn example using D3 JavaScript SVG rendering Framework: https://github.com/stephenlb/pubnub-mongo-pipe/blob/master/phone/map.html
NOTE: This is only a starting point and provides you with references on getting started to make it easy and simple, yet flexible based on the direction you will be taking your app.
Next Steps to Piece Together the Real-time Geo Map
You will next want to do the following to complete the process and join together all the separate components listed here.
Modify the map.html page for your purposes to display always-visible dots. Note that in the video the dots are temporary beacons that display and vanish rapidly. You'll want to make them persist on the map. This is basically the "Make it look the way you want it" step.
Decide how and when you want to trigger the TCP Socket Push events from PHP or MySQL directly. I'd recommend the PHP approach.

Passing php array to javascript

I have created a Google Map using JavaScript (v3 api). I have popped a couple of markers onto this, just to show it can be done. I have added some text to a text box specific to each marker, just to see if it can be done. Both marker and text box are ugly, but that's a problem for a different day. The map takes up around 75% of screen width and 100% screen height.
I have a mySQL db of user posts. The data includes a post #id, a category, an ip address, a longitude value, a latitude value, a city, a user name, a heading and post content.
I have 'floated' a table containing post category and heading up beside the map, using PHP to query the db, shoving the db rows into an array and using this as the source for the table. This takes up the remainder of the display width.
Fine, so far.
I want to add a marker for each post so that the marker is located at the longitude and latitude from which the post originated. I want to add content to a marker text box that is specific to that post (e.g. city, user name, post heading, post content).
Further, I want to be able to link the posts in the displayed table to the map markers so that, for instance, a mouse-over event on a particular post in the table might cause the text box associated with that marker to become visible.
But I cannot seem to find a way to pass the PHP array to the Google Map JavaScript so that I can use this to add the markers as required.
Nor have I yet been able to find a way to associate a mouse over event on an object external to a Google map to a Google map marker.
I have done extensive research and have found similar requests for the former - passing a PHP array to JavaScript. The suggested solution is usually to create a string from the PHP array with some sort of separator, e.g. a comma, and pass this to JavaScript where it is reformed into an array. I do not believe this would work in my case.
My current code resides in a single file. The style stuff is located in a style section in the html head section and can be moved to a separate css file later. The Google map JavaScript are in script sections, again in the html head and can be moved to a separate js file. The body contains just a little html - divs for the map-canvas and the table with PHP
to acquire the database rows in a single PHP array and to create the html for the table.
I am aware that 'PHP is server side technology while JavaScript is client side' as has been indicated many times.
But surely there must be some way to pass an array of data obtained by PHP from a SQL db (not that the data origin is particularly relevant) to JavaScript code?
I apologise for being so verbose, and if my questions have been answered somewhere I have missed, or misunderstood. Or if I am being particularly stupid.
Take care.
Mike
Adding this by editing the original post.
OK. I might have found an answer to my second question: how to create a link from an external element to a Google map marker. http://econym.org.uk/gmap/mouseover.htm Always the way, after giving up looking for something that item is found.
Mike
Convert your PHP array to JSON, using json_encode.
Now you have a JavaScript object you can use.
$jsonString = json_encode($phpArray);
In javascript:-
var jsonStr = <?=$jsonString?>;

Is it possible to add an overlay in google maps api on user side e.g. with rmb click?

I'm working on a project of mine, which would require users to add markers on a google maps api map, that would be later on passed to a DB, which would store all overlay coordinates and once the map is loaded (in case the user has the required permissions, of course), a for loop will add all markers from the DB into the page and will visualize them (circles with static radius, but various coordinates). So long story short, I need a way to enable the users to put those markers themselves there and a way to read the LatLng coordinates and pass them to a script, which will flush them in the DB. One way (in case it's possible, of course) is to use the context menu and add an option like "set marker here", that would pass the coords to a function flushing them to the DB. Of course the workaround is RMB-> what is here, copy the coords and enter 'em in a input field, which almost inevitably will doom the project to an epic fail, because nobody will do that, but instead will just enter some random numbers, which would be moronic, because the project basically depends on those coordinates.
So is there a way to somehow automate the adding process of an overlay element in the api, that I could use? I googled around for a few days, tried to find something in the v3 help too, but didn't find anything really helpful so far..
Thanks in advance! All comments and help would be appreciated!
Cheers,
vlex

How to do search with out using the scripting language and by using jquery?

I have a html site. In that site around 100 html files are available. i want to develop the search engine . If the user typing any word and enter search then i want to display the related contents with the keyword. Is't possible to do without using any server side scripting? And it's possible to implement by using jquery or javascript?? Please let me know if you have any ideas!!!
Advance thanks.
Possible? Yes. You can download all the files via AJAX, save their contents in an array of strings, and search the array.
The performance however would be dreadful. If you need full text search, then for any decent performance you will need a database and a special fulltext search engine.
3 means:
Series of Ajax indexing requests: very slow, not recommended
Use a DB to store key terms/page refernces and perform a fulltext search
Utilise off the shelf functionality, such as that offered by google
The only way this can work is if you have a list of all the pages on the page you are searching from. So you could do this:
pages = new Array("page1.htm","page2.htm"...)
and so on. The problem with that is that to search for the results, the browser would need to do a GET request for every page:
for (var i in pages)
$.get(pages[i], function (result) { searchThisPage(result) });
Doing that 100 times would mean a long wait for the user. Another way I can think of is to have all the content served in an array:
pages = {
"index" : "Some content for the index",
"second_page" : "Some content for the second page",
etc...
}
Then each page could reference this one script to get all the content, include the content for itself in its own content section, and use the rest for searching. If you have a lot of data, this would be a lot to load in one go when the user first arrives at your site.
The final option I can think of is to use the Google search API: http://code.google.com/apis/customsearch/v1/overview.html
Quite simply - no.
Client-side javascript runs in the client's browser. The client does not have any way to know about the contents of the documents within your domain. If you want to do a search, you'll need to do it server-side and then return the appropriate HTML to the client.
The only way to technically do this client-side would be to send the client all the data about all of the documents, and then get them to do the searching via some JS function. And that's ridiculously inefficient, such that there is no excuse for getting them to do so when it's easier, lighter-weight and more efficient to simply maintain a search database on the server (likely through some nicely-packaged third party library) and use that.
some useful resources
http://johnmc.co/llum/how-to-build-search-into-your-site-with-jquery-and-yahoo/
http://tutorialzine.com/2010/09/google-powered-site-search-ajax-jquery/
http://plugins.jquery.com/project/gss
If your site is allowing search engine indexing, then fcalderan's approach is definitely the simplest approach.
If not, it is possible to generate a text file that serves as an index of the HTML files. This would probably be rudimentarily successful, but it is possible. You could use something like the keywording in Toby Segaran's book to build a JSON text file. Then, use jQuery to load up the text file and find the instances of the keywords, unique the resultant filenames and display the results.

How should I go about this?

I have a MySQL Database of more or less 100 teachers, their names, and their phone numbers, stored in tables based upon their department at the school. I'm creating an iPhone app, and I've found that UITableViews and all the work that comes with it is just too time consuming and too confusing. Instead, I've been trying to create a web page on my server that loads all the data from MySQL and displays it using HTML, PHP, jQuery, and jQTouch for formatting.
My concept is that the separators will be by department, and the staff will be sorted alphabetically under each department. On the main page, each person's name will be clickable so they can go to ANOTHER page listing their name, email address, and telephone number, all linked so that the user can tap on the email or number and immediately email or call that person, respectively.
HOWEVER, I am completely at a loss for how I should start. Can anyone point me in the right direction for displaying the data? Am I going about it wrong in using PHP? Should I opt for something COMPLETELY different?
PHP to manage the database interaction and generate HTML is fine. There are heaps of tutorials on how to do that (e.g. http://www.w3schools.com/PHP/php_mysql_intro.asp) How to make it look nice is beyond the scope of this answer, and I'd recommend you search for table/CSS examples to get some ideas of what looks good and how they're implemented. If you need interactivity such as expanding rows or changing colors, then jQuery would be an appropriate next step, though you certainly don't need more than HTML + CSS for a nice looking table representation.
What I don't know about is the auto email/call functionality you're after, and whether you can get that "for free" from whatever is rendering the HTML. That's iPhone specific, not PHP/jQuery/etc... And I'd second Alex's advice that if UITableView is the right tool for the job then you will definitely be better off in the long run just buckling down and learning it. (And going through that will probably make pickup up other parts of the API much easier to boot.)
Instead of loading my PHP in my <body>, I created a function that retrieved the data via mysql_fetch_assoc(), which added all the information and created each individual div of data AS WELL AS injecting a <script> to $.append() the list item content for each item retrieved via the mysql_fetch_assoc(). Thanks for the responses anyway!

Categories