I have this code
http://jsfiddle.net/DanielMontenegro/7pdU4/3/
Now, supose that I want to put that map in a site to allow people to report some particular event through the geocoding service. I would like to ask how could I manage to get the address/coordinates of that event in a table, and gatherall the users reports into a single database.
There is a lot of goood information about interfacing the Google Maps API v3 with PHP/MySQL in the "Articles" section of the documentation
This one looks like it answers your question; From Info Windows to a Database: Saving User-Added Form Data
See below code and try it.
I am using php static array you can connect your database and create array according your requirement. see the array below.
<?php $item = array('jaipur, rajasthan,india', 'udaipur, rajasthan,india'); ?>
Below My Code Take a look.
<html>
<head>
<script src="http://maps.google.com/maps?file=api&v=2&key=AIzaSyDwFjOazEAe1MI7nHV6vUwkWytOp8LH2Zk" type="text/javascript"></script>
</head>
<body onload="initialize();">
<?php $item = array('jaipur, rajasthan,india', 'udaipur, rajasthan,india'); ?>
<script>
var map = null;
var geocoder = null;
function initialize() {
if (GBrowserIsCompatible()) {
map = new GMap2(document.getElementById("map_canvas"));
var addresses = ["<?php echo implode ('","', $item); ?>"]
var geocoder = new GClientGeocoder();
//var addresses = ["A II Z, Ibn Battuta Mall, Sheikh Zayed Road, 5th Interchange, Jebel Ali Village, Dubai","A. Testoni,Dubai Festival City Mall, Ground Floor, Dubai", "Abdulla Hussain Khunji, The Dubai Mall,Downtown, Abu Dhabi"];
var curIndex = 0;
function showAddress() {
var _cur = addresses[curIndex];
geocoder.getLatLng(
_cur,
function(point) {
if (!point) {
//alert(_cur + " not found");
//map.setCenter(new GLatLng(0, 0), 6);
//map.setUIToDefault();
} else {
//console.log(_cur+":"+point);
//alert(_cur);
var cafeIcon = new GIcon(G_DEFAULT_ICON);
// Set up our GMarkerOptions object
markerOptions = { icon:cafeIcon };
map.setCenter(point, 6);
var marker = new GMarker(point, markerOptions);
map.addOverlay(marker);
var sales = new Array();
sales = _cur.split("|");
//Add click event on push pin to open info window on click of the icon
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml("<p class='para1bold' style=\"font-weight: bold;\">Address <br /><span class='para1' style='font-weight:normal;'>" + sales[1] + "</span></p>");
});
//Provides map,satellite,hybrid and terrain views in the map along with zoom control
map.setUIToDefault();
}
//do next after done
curIndex++;
if(curIndex<addresses.length)
showAddress();
}
);
}
showAddress();
}
}
</script>
<div id="map_canvas" style="width:100%; height:750px;"></div>
</body>
</html>
You'll need to set up an action listener of some kind (preferably a listener that will listen for a user click on the map). Then, simply geocode the resulting lat/lng and store what you receive in your table.
User clicks a point on map.
Click event grabs what lat/lng the user clicked on.
The Lat/lng is geocoded for a textual address using Ajax.
Both Lat/lng and textual address are stored side-by-side in your database table.
Related
I am using google geocode to convert an address into lat/lng coordinates and then searching my db for other 'articles'(actually store addresses) that are nearby. This is working and my 'locations' foreach loop works fine (If I look at the console I see an array). But when I go to add my markers nothing shows up. I'm not getting any errors with the code below but if I console.log(lat) it shows NaN.
The map shows up and it is centering correctly according to the var 'myLatlng', but no makers are showing. I saw on SO (HERE) that geocode creates a string so you need to parse string to float. But my attempt below is not working.
I'm using laravel 5.
If you want to see how I got my lat/lng coordinates see my answer to me own question HERE.
My template.blade.php page has this:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=MYKEY&signed_in=true&libraries=places"></script>
The page I have the map has the script below these script tags.
Here's the relevant code for the page I have the map on. articles.index.blade.php
#section('footer')
<script>
function initialize() {
var map_canvas = document.getElementById('map_canvas');
var myLatlng = new google.maps.LatLng(parseFloat({{ $article->lat }}),parseFloat({{ $article->lng }}));
var map_options = {
center: myLatlng,
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(map_canvas, map_options)
var locations = [
#foreach($articles as $article)
[{{$article->lat}}, {{$article->lng}}]
#endforeach
];
var lat = parseFloat(locations[0]);
var lon = parseFloat(locations[1]);
for (i = 0; i < locations.length; i++) {
var location = new google.maps.LatLng(lat, lon);
var marker = new google.maps.Marker({
position: location,
map: map,
});
}
}
google.maps.event.addDomListener(window, "load", initialize);
</script>
#stop
If I understood properly. You have this 'locations' array. Right? and those are the locations where the markers should appear. But if I'm not wrong, you could have a syntax error in this line:
var locations = [
#foreach($articles as $article)
[{{$article->lat}}, {{$article->lng}}], //YOU NEED A COMMA TO SEPARATE EACH ELEMENT
#endforeach
];
Might be the API is not understanding that weird array with no commas separating each child :P
I want you to try this different logic and see if it works in this part:
//var lat = parseFloat(locations[0]); REMOVE THIS
//var lon = parseFloat(locations[1]); AND THIS
for (i = 0; i < locations.length; i++) {
var location = new google.maps.LatLng(locations[i][0], locations[i][1]);
var marker = new google.maps.Marker({
position: location,
map: map,
});
}
Leave the type as a String, no need to convert to float.
I am trying get all coordinates of India. I have tried with http://maps.google.com/maps/api/geocode/json?sensor=true&address=India.
In this i am getting only bounds of southEast, northWest.
But i need complete list of all coordinates which will exactly match india polygon.
I have tried with twitter API. But its giving rectangular area coordinates of the country like below.
I need exact polygon coordinates. Any suggestion?
You can make use of natural earth data fusion table for countries. It's public table & downloadable. Here is a demo. I used a temp API key in demo which I'll remove after some time.
HTML:
<html>
<head>
<title>Google Maps API v3 : Fusion Tables Layer</title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
</script>
</head>
<body onload="initialize()">
<div id="map" style="width: 530px; height:230px">
</div>
<div id="datadiv"></div>
</body>
</html>
Javascript:
function initialize()
{
map = new google.maps.Map(document.getElementById('map'),
{
center: new google.maps.LatLng(22.7964,79.5410),
zoom: 4,
mapTypeId: 'roadmap'
});
layer = new google.maps.FusionTablesLayer({query: {
select: '\'wkt_4326\'',
from: '1uKyspg-HkChMIntZ0N376lMpRzduIjr85UYPpQ',
where:'sov_a3=\'IND\''
}});
debugger
layer.setMap(map);
getData('1uKyspg-HkChMIntZ0N376lMpRzduIjr85UYPpQ');
}
function getData(table) {
// Builds a Fusion Tables SQL query and hands the result to dataHandler()
var queryUrl = 'https://www.googleapis.com/fusiontables/v1/query?sql=';
var queryUrlParams = '&key=GET_YOUR_API_KEY_FROM_GOOGLE&jsonCallback=?'; // ? could be a function name
var query = "SELECT * FROM " + table + " where sov_a3='IND'";
var queryurl = encodeURI(queryUrl + query + queryUrlParams);
//Get fusion table data
$.get(queryurl,showData);
}
function showData(d) {
debugger
var data = d.rows[0];
$("#datadiv").html(data);
}
I have one array with coordinates (lat, long)...
This array has about 60-80 items...
In my foreach cycle there are...
...{
$lat = substr($xx[1],0,8);
$long = substr($xx[0],0,8);
?>
<script type="text/javascript">
// <![CDATA[
$(function() {
var geocoder = new google.maps.Geocoder();
function geocodePosition(pos,pos2) {
geocoder.geocode({
latLng: new google.maps.LatLng(pos,pos2)
}, function(responses) {
if (responses && responses.length > 0) {
console.log(responses[0].formatted_address);
} else {
console.log('Cannot determine address at this location.');
}
});
}
geocodePosition(<?php echo $lat ?>,<?php echo $long ?>);
});
// ]]>
</script>
<?php } ...
Geocoder geocodes at the most 5 coordinates, others come with output 'Cannot determine address at this location.'
When I take some of those, which "could not be determined", I use them manually (just 1 item = lat and long, not the whole array) it works.
So where's the problem?
You cant request addresses too fast in a row (blocked by google), you need to use small setTimeout() between when doing it inside loop. Also note that you can request only 2500 addresses per day with basic api, with business over 100000 source from google.
How to avoid google map geocode limit
Setting timeout to simulate pause
Geocode markers from PHP array
Avoid geocode limit - js / html source
I really am a JS noob - I have never really used itbefore and am struggling using the marker clusterer google provide. I have rad the documentation
here is the code
<script src="http://localhost/wheredidmytweetgo/js/markercluster.js" type="text/javascript"></script>
<script type="text/javascript">
//<![CDATA[
function load() {
if (GBrowserIsCompatible()) {
var map = new GMap2(
document.getElementById("map"));
map.addControl(new GSmallMapControl());
map.setCenter(
new GLatLng( 56.65622649350222, -19.86328125), 2);
var mc = new MarkerClusterer(map);
function createMarker(point, text, title) {
var marker =
new GMarker(point,{title:title});
GEvent.addListener(
marker, "click", function() {
marker.openInfoWindowHtml(text);
});
return marker;
}
<?php
foreach ($cluster_location as $location) {
?>
var marker = createMarker(
new GLatLng(<?php echo $location ?>),
'Marker text <?php echo $location ?>',
'Example Title text <?php echo $location ?>');
map.addMarker(marker);
<?php }
?>
}
}
cluster location is just an array of lat and longs - My code is working fine when just using the add.overlay however there are too many to make the map readable hence the need for clustering. I do load the clustering JS which I have I have included.
I create the clusterer object and pass in map as defined.
var markers = [];
//create array
I know I can create a JS array and pass this in to
var mc = new MarkerClusterer(map, markers);
But I simply dont have the JS knowledge to create an array at this time (I intend to learn) and the Google documentation advises you can iterate and add one at a time using addMarker
Hi Tom - Thanksfor the info - I have tried doing what you advised and have came up with the below:
<script src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="http://localhost/wheredidmytweetgo/js/markercluster.js">
</script>
<script type="text/javascript">
function initialize() {
var center = new google.maps.LatLng(37.4419, -122.1419);
var map = new google.maps.Map(document.getElementById('map'), {
'zoom': 13,
'center': center,
'mapTypeId': google.maps.MapTypeId.ROADMAP
});
var markers = [];
<?php foreach ($cluster_location as $location) { ?>{
var marker = new google.maps.Marker({'position': <?php echo $location;?>});
markers.push(marker);
}
<?
}
?>
var markerCluster = new MarkerClusterer(map, markers);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<h3>A simple example of MarkerClusterer (100 markers)</h3>
<p>
Compiled |
Standard version of the script.
</p>
<div id="map-container"><div id="map"></div></div>
</body>
</html>
But my map still loads empty. I'm using literally the most basic google provided code now and just loading my own markers in. I know my markers positioning should be okay because when I go to view my page source I can see
{
var marker = new google.maps.Marker({'position': 40.0994425,-74.9325683});
markers.push(marker);
});
for each marker. any more help would really be appreciated!
Please check the examples on google maps utilities library page (link).
But basically to add instance of an object (a marker) to an array you have to define the array first so you need to do the var markers = []; above the loop where you create the markers. And then as you create the markers you have to add them to the markers array by calling the push method of an array (while you are at it go to MDN and read about arrays! if you want to learn it's good time to start there - there is a tutorial about JS there as well (link).
So inside of the foreach loop afer you've defined a marker just add it to the array markers.push(marker); This will make the markers available for the MarkerCluster initialization.
In a longer term when you figure out javascript a bit better you'll probably want to replace this part with either passing data as JSON object to the DOM so methods can handle it or even better - have the data for markers be retrieved with ajax query. But one step at a time I guess :)
Maybe try the fun interactive tutorials at the www.codecademy.com? They are quite basic but seems like that's exactly what you need
EDIT:
var marker,
markers = [];
<?php foreach ($cluster_location as $location) { ?>
marker = new google.maps.Marker({'position': <?php echo $location;?>});
markers.push(marker);
<? } ?>
I have a MySQL database where I stored some marker position (along with some other information) which I loaded into google map. I followed the example -
http://code.google.com/apis/maps/articles/phpsqlajax.html
and it worked fine for me.
Now what I want to do is, suppose a user will be able to choose an id of a specific marker and clicking on a button it will be loaded onto the map. Not sure how to load the specific marker on the map dynamically.
Any sort of help will be appreciated.
I have set up an example here. I am using the Google Geocoding API to receive co-ordinates of the address entered by the user and creating the marker using Google API V3 as shown below
Ajax Request to get the co-ordinates
$.getJSON("getjson.php?address="+address,
function(data){
lat=data.results[0].geometry.location.lat;
lng=data.results[0].geometry.location.lng;
point= new google.maps.LatLng(lat,lng);
map.setCenter(point);
zoom = 14;
marker = createMarker(point,"<h3>Marker"+(markersArray.length+1)+" "+point+"</h3>",zoom);
});
PHP Code to return the co-ordinates
<?php
$address = $_GET['address'];
$address=str_replace(" ","+",$address);
if ($address) {
$json = file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?address='.$address.
'&sensor=true');
echo $json;
}
?>
Creating the Marker
function createMarker(latlng, html,zoom) {
var contentString = html;
var marker = new google.maps.Marker({
position: latlng,
map: map,
zIndex: Math.round(latlng.lat()*-100000)<<5
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(contentString);
infowindow.open(map,marker);
});
marker.MyZoom = zoom;
return marker;
}
First of all i see in your link that you use v2.Try to use v3 at least now that you are at the beginning since the v2 is deprecated.
As of your question i can only tell you the procedure and then you can make it happen.
1. User interaction
User interacts with UI and selects i.e. a range of prices(0-100).
2. Ajax request
The client sends an ajax request to server to get json with jquery getJson() or any other way.
3. Server Respond
A php page responds to your ajax call and make a query in mysql getting a resultset of position-markers,converts it in json and send it back.
4. Parse respond
Parse the json back to the client and create markers.
Hi I found this one great help
http://www.svennerberg.com/2012/03/adding-multiple-markers-to-google-maps-from-json/
Create a json object as given the link and pass it to javascript .
function createMarker(json){
for (var i = 0, length = json.length; i < length; i++) {
var data = json[i],
latLng = new google.maps.LatLng(data.lat, data.lng);
// Creating a marker and putting it on the map
var marker = new google.maps.Marker({
position: latLng,
map: map,
title: data.title
});
}
}