I am working in joomla 2.5 and I have to create a module for Google map and using Google map api v2.
and I am using geocoder = new GClientGeocoder(); but it is now working
output image:-
My html <div> tag
<div id="map_canvas" style="width: 800px; height:800px;"></div>
My script
<script>
//<![CDATA[
var map = null;
var geocoder = null;
function initialize() {
if (GBrowserIsCompatible()) {
//calls map to appear inside <div> with id, "map_canvas"
map = new GMap2(document.getElementById("map_canvas"));
//adds zoom and arrow controls to map
geocoder = new GClientGeocoder();
map.setMapType(G_SATELLITE_MAP);
var allAddress = "Dubai~Abu Dhabi";
var addresses = new Array();
addresses = allAddress.split("~");
var curIndex = 0;
function showAddress() {
var _cur = addresses[curIndex];
geocoder.getLatLng(
_cur,
function(point) {
alert(_cur);
if (!point) {
alert(_cur + " not found");
} else {
alert(_cur+":"+point);
}
//do next after done
curIndex++;
if(curIndex<addresses.length)
showAddress();
}
);
}
showAddress();
}
}
//]]>
</script>
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>
Related
How to save a google maps marker data into mysql DB ? using php .
And is it possible to prevent dragging that marker out of a certain country ? or maybe validating if the data is out of the wanted country when clicking on submit for example.
Yes, no problem.
The database part, you will have to do yourself. I provide you 'ajax.php'; where you receive the POST data. All I do, is print the SQL-string.
The country is Belgium, feel free to change this (now on line 39). When ever the client drops the marker anywhere but in Belgium, the marker is sent back to the position where the client started dragging
ajax.php
<?php
if($_SERVER['REQUEST_METHOD'] === 'POST') {
$sql = "INSERT INTO markers (lat, lng) VALUES (". (float) $_POST['lat'] .", ". (float) $_POST['lng'] .");";
echo $sql;
}
?>
index.php
<div id="map-canvas"></div>
<div class="controls">
<input type="button" value="SAVE" id="save_marker">
</div>
<div id="display"></div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://maps.googleapis.com/maps/api/js?libraries=geometry&sensor=false"></script>
<script>
///////////////////////
// Ajax / upload part
$(document).ready(function() {
// initialize Google Maps
initialize();
// save marker to database
$('#save_marker').click(function() {
// we read the position of the marker and send it via AJAX
var position = marker.getPosition();
$.ajax({
url: 'ajax.php',
type: 'post',
data: {
lat: position.lat(),
lng: position.lng()
},
success: function(response) {
// we print the INSERT query to #display
$('#display').html(response);
}
});
});
});
///////////////////////
//Google Maps part
var map = null;
var marker = null;
var country = 'BE'; // Belgium. Feel free to use this script on any other country
// Google Maps
function initialize() {
var startDragPosition = null;
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(50.5, 4.5), // Over Belgium
mapTypeId: google.maps.MapTypeId.TERRAIN
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
// set the new marker
marker = new google.maps.Marker({
position: new google.maps.LatLng(50.5, 4.5),
map: map,
draggable: true
});
var myGeocoder = new google.maps.Geocoder();
// set a callback for the start and end of dragging
google.maps.event.addListener(marker,'dragstart',function(event) {
// we remember the position from which the marker started.
// If the marker is dropped in an other country, we will set the marker back to this position
startDragPosition = marker.getPosition();
});
google.maps.event.addListener(marker,'dragend',function(event) {
// now we have to see if the country is the right country.
myGeocoder.geocode({'latLng': marker.getPosition()}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK && results[1]) {
var countryMarker = addresComponent('country', results[1], true);
if (country != countryMarker) {
// we set the marker back
marker.setPosition(startDragPosition);
}
}
else {
// geocoder didn't find anything. So let's presume the position is invalid
marker.setPosition(startDragPosition);
}
});
});
}
/**
* geocodeResponse is an object full of address data.
* This function will "fish" for the right value
*
* example: type = 'postal_code' =>
* geocodeResponse.address_components[5].types[1] = 'postal_code'
* geocodeResponse.address_components[5].long_name = '1000'
*
* type = 'route' =>
* geocodeResponse.address_components[1].types[1] = 'route'
* geocodeResponse.address_components[1].long_name = 'Wetstraat'
*/
function addresComponent(type, geocodeResponse, shortName) {
for(var i=0; i < geocodeResponse.address_components.length; i++) {
for (var j=0; j < geocodeResponse.address_components[i].types.length; j++) {
if (geocodeResponse.address_components[i].types[j] == type) {
if (shortName) {
return geocodeResponse.address_components[i].short_name;
}
else {
return geocodeResponse.address_components[i].long_name;
}
}
}
}
return '';
}
</script>
<style>
#map-canvas {
height:400px;
}
</style>
I am using a google map in a PHP/MYSQL application. I get the code for the map form Goolge Docs and adapted a bit for the application.
New modifications are comming in the application and now the application need to know the 'current zoom level of the google map'. I check in internet but I didn't find a clear answer.
Is it possible to do it ? Is it mandatory to reload the page in every zoom change ?
This is the code and thanks.
<code>
function load() {
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(latitude,longitude),
zoom: zoommapa,
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.LARGE
},
mapTypeId: 'roadmap'
});
// drap center
var image = 'images/icons/etapa/etapa.png';
var myLatLng = new google.maps.LatLng(latitude,longitude);
var beachMarker = new google.maps.Marker({
position: myLatLng,
map: map,
icon: image
});
var infoWindow = new google.maps.InfoWindow;
// Change this depending on the name of your PHP file
downloadUrl("marquers_motor_3.php", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
//var name = 1;
var markers2 = [];
for (var i = 0; i < markers.length; i++) {
//var name = markers[i].getAttribute("name");
var image = markers[i].getAttribute("image");
var sombra = markers[i].getAttribute("sombra");
var address = markers[i].getAttribute("address");
var type = markers[i].getAttribute("type");
var orden = markers[i].getAttribute("order");
var name = markers[i].getAttribute("name"); // web_site email ciudad pais
var web_site = markers[i].getAttribute("web_site");
var email = markers[i].getAttribute("email");
var ciudad = markers[i].getAttribute("ciudad");
var pais = markers[i].getAttribute("pais");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
if (ciudad =="" || ciudad =='Desconocido') { ciudad = ""} else {ciudad =ciudad + " " }
if (!(web_site =="")) {web_site = "<a href='" + web_site + "' class='list' target='_blank'>" + web_site +"</a>"+"<br>"} else {web_site =""}
var html = "<div id='infoWindow'>" + orden + " - " + name + "<br>" + web_site + ciudad + " " + pais + "</div>";
//var name = name + 1;
var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: image,
shadow: sombra
});
var marker2 = new google.maps.Marker({
position: point
});
markers2.push(marker);
bindInfoWindow(marker, map, infoWindow, html);
}
});
var mcOptions = {gridSize: 50, maxZoom: 15};
var MarkerClusterer = new MarkerClusterer(map, markers2,mcOptions);
}
function bindInfoWindow(marker, map, infoWindow, html) {
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
//]]>
//google.maps.event.addDomListener(window, 'load', initialize);
I assume the application needs to know the zoom level, but the zoom level is in user space (client side).
get the zoom level from the map with javascript (see https://developers.google.com/maps/documentation/javascript/reference?hl=nl#Map)
map.getZoom();
This has to be send back to the server using AJAX calls
Server can do with the zoom level what it wants
Keep in mind the fact that if multiple users can open the same map, zoom levels can be different so what would be the required behavior?
Yes, you can get the current zoom level of the map with the getZoom method of the google.maps.Map object.
If you need to trigger a method when the zoom changed then you can listen to the zoom_changed event of the google.maps.Map object. For further information about google.maps.Map object read: this
Consider the following example (to make it work: copy in notepad save the file as html and run it with Chrome):
<!DOCTYPE html>
<html>
<head>
<title>Getting Zoom Demo</title>
<style type="text/css">
html, body{ height: 100%; height: 100%; margin: 0; padding: 0; }
#map-container{ height: 100%; width: 100%; min-width:500px; min-height:300px; }
</style>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
</head>
<body>
<div>
<label id="display-zoom-label">
</label>
</div>
<div id="map-container"></div>
<script>
// Global map variable to have access to map object everywhere in the code
var map,
firstBoundChangedListener,
markers = [];
// Add random markers
function addMarkers(count) {
// map is the google.maps.Map object
var bounds = map.getBounds();
var northEast = bounds.getNorthEast();
var southWest = bounds.getSouthWest();
var minLat = Math.min(northEast.lat(), southWest.lat());
var maxLat = Math.max(northEast.lat(), southWest.lat());
var minLng = Math.min(northEast.lng(), southWest.lng());
var maxLng = Math.max(northEast.lng(), southWest.lng());
var latDifference = maxLat - minLat;
var lngDifference = maxLng - minLng;
var latLngArray = new Array();
for (var i = 0; i < count; i++) {
var lat = minLat + Math.random() * latDifference;
var lng = minLng + Math.random() * lngDifference;
var latLng = new google.maps.LatLng(lat, lng);
latLngArray.push(latLng);
}
for (var i = 0; i < latLngArray.length; i++) {
var marker = new google.maps.Marker({
position: latLngArray[i],
title: "Marker: " + i
});
markers.push(marker);
marker.setMap(map);
}
}
function UpdateZoomLabel() {
var displayZoomLabel = document.getElementById("display-zoom-label"),
// get current zoom
zoomValue = map.getZoom();
displayZoomLabel.innerHTML = "The Current Map's Zoom is: " + zoomValue;
}
// Initialize the map object
function initialize() {
var latlng = new google.maps.LatLng(-34.397, 150.644);
var mapOptions = {
zoom: 8,
center: latlng
};
map = new google.maps.Map(document.getElementById('map-container'), mapOptions);
firstBoundChangedListener = google.maps.event.addListener(map, "bounds_changed", function () {
if (firstBoundChangedListener) google.maps.event.removeListener(firstBoundChangedListener);
// call add markers: add 'n' markers randomly
addMarkers(6);
});
//Listen for the 'zoom_changed' event of the map
google.maps.event.addListener(map, "zoom_changed", function () {
//show zoom in label
UpdateZoomLabel();
});
UpdateZoomLabel();
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</body>
</html>
I have seen this link:
Google map api v3 add polylines from array
this is somehow slightly the same as my problem.. you see, im getting a javscript error as such this:
Uncaught TypeError: Cannot call method 'getPath' of undefined
AddCoordinate map:118
(anonymous function)
well my code is basically populating the coordinates first as the page is loaded together with the map.. And by the time that click is triggered (html button), that is the only time that the map will be plotted with poly lines.. I hope I explained it very well though.. Here's what i got:
var map;
var Markers = [];
var Coordinates = [];
var LinePath;
function initialize()
{
var myLatLng = new google.maps.LatLng(21.291982, -140.821856);
var myOptions = {
zoom: 3,
center: myLatLng,
mapTypeId: google.maps.MapTypeId.SATELLITE
};
var MarkerSize = new google.maps.Size(48,48);
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}
function AddCoordinate( lat, long ) {
var path = LinePath.getPath();
path.push( new google.maps.LatLng( lat, long ) );
LinePath.setPath(path);
}
function PlotLine()
{
LinePath = new google.maps.Polyline({
path:Coordinates,
strokeColor:"#ffffff",
strokeOpacity:1.0,
strokeWeight:5
});
LinePath.setMap(map);
}
<html>
<body onload="initialize()">
<div id="map_canvas" ></div>
<?php
foreach($arrayOfPlotPoints as $key => $value){
$longitude = round($value['longitude'],5);
$latitude = round($value['latitude'],5);
$snrLevel = $value['snr_level'];
echo '<script type="text/javascript">AddCoordinate('.$latitude.','.$longitude.')</script>';
?>
<option value="<?php echo $longitude.",".$latitude.",".$snrLevel?>"> Lg:<?php echo $longitude." Lt: ".$latitude." LV: ".$snrLevel?></option>
<?php } ?>
</select>
<br /><br />
<?php echo $this->Form->button('PLOT', array('type'=>'button', 'onclick'=>'PlotLine()')); ?>
echo $this->Form->button('PLOT', array('type'=>'button', 'onclick'=>'PlotLine()'));
?>
********EDITED**********
i have made a partial modification of my code.. however im getting the same error..
Uncaught TypeError: Cannot call method 'getPath' of undefined
AddCoordinate (anonymous function)
function initialize() {
//.....
LinePath = new google.maps.Polyline({
path:Coordinates, //san ka galing Coordinates??? dineclare ka pero di ka aman nilagyan "YATA" ng laman
strokeColor:"#ffffff",
strokeOpacity:1.0,
strokeWeight:5
});
}
function AddCoordinate( latitude, longitude ) {
var path = LinePath.getPath();
path.push( latitude, longitude );
}
function PlotLine()
{
LinePath = new google.maps.Polyline({
path:Coordinates,
strokeColor:"#ffffff",
strokeOpacity:1.0,
strokeWeight:5
});
LinePath.setMap(map);
}
<HTML>
select name="long_and_lat" id="long_and_lat" style="width:220px;height:250px;" size="100">
<?php
$plotPoints = array();
foreach($arrayOfPlotPoints as $key => $value){
$longitude = round($value['longitude'],5);
$latitude = round($value['latitude'],5);
$snrLevel = $value['snr_level'];
echo '<script type="text/javascript">AddCoordinate('.$latitude.','.$longitude.')</script>';
?>
<option value="<?php echo $longitude.",".$latitude.",".$snrLevel?>"> Lg:<?php echo $longitude." Lt: ".$latitude." LV: ".$snrLevel?></option>
<?php } ?>
</select>
<br /><br />
<?php echo $this->Form->button('PLOT', array('type'=>'button', 'onclick'=>'PlotLine()')); ?>
</html>
You are making a call to LinePath in AddCoordinate(), but LinePath isn't created until PlotLine() is called (by clicking the button).
Perhaps you could create LinePath when you declare it, then just call LinePath.setMap(map); from PlotLine().
Maybe something like this:
<html>
<head>
<link href="https://google-developers.appspot.com/maps/documentation/javascript/examples/default.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var map;
var Markers = [];
var Coordinates = [];
var LinePath = new google.maps.Polyline({
path:Coordinates,
strokeColor:"#ffffff",
strokeOpacity:1.0,
strokeWeight:5
});
function initialize()
{
var myLatLng = new google.maps.LatLng(21.291982, -140.821856);
var myOptions = {
zoom: 3,
center: myLatLng,
mapTypeId: google.maps.MapTypeId.SATELLITE
};
var MarkerSize = new google.maps.Size(48,48);
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}
function AddCoordinate( lat, long ) {
var path = LinePath.getPath();
path.push( new google.maps.LatLng( lat, long ) );
LinePath.setPath(path);
}
function PlotLine()
{
LinePath.setMap(map);
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas" ></div>
<script type="text/javascript">AddCoordinate(11,12)</script>
</body>
</html>
I'm trying to display an array of postcodes onto a google map using PHP and using the Symfony Framework (1.0)
The main problem I am having, is that there is some text associated with each marker, i.e when you click the marker a popup appears.
The main problem is that the text should point to the correct postcode/marker on the map, but for some reason this doesn't seem to be the case:
<?php
$addresses = array();
foreach($contents->getResults() as $content):
$addresses[] = array(
'postcode'=>sprintf('%s',str_replace(' ','',$content->getPostalCode())),
'html'=>escape_javascript(get_partial('property/propertyList',array('content'=>$content))),
);
endforeach;
?>
<?php
echo javascript_tag("
var map;
var localSearch = new GlocalSearch();
var center = false;
var icon = new GIcon();
icon.image = 'http://www.google.com/mapfiles/marker.png';
icon.shadow = 'http://www.google.com/mapfiles/shadow50.png';
icon.iconSize = new GSize(20, 34);
icon.shadowSize = new GSize(37, 34);
icon.iconAnchor = new GPoint(10, 34);
var delay = 100;
var bounds = new GLatLngBounds();
var addresses = ".json_encode($addresses).";
var nextAddress = 0;
function theNext() {
if (nextAddress < addresses.length) {
var postcode = addresses[nextAddress].postcode;;
var html = addresses[nextAddress].html
setTimeout('getAddress(\"'+postcode+'\",\"'+html+'\",theNext)', delay);
nextAddress++;
}
}
function getAddress(search, html, next) {
usePointFromPostcode(search, html);
next();
}
var geoCount = 0;
function usePointFromPostcode(address, html, callbackFunction) {
localSearch.setSearchCompleteCallback(null,
function() {
if (localSearch.results[0])
{
geoCount++;
var resultLat = localSearch.results[0].lat;
var resultLng = localSearch.results[0].lng;
var point = new GLatLng(resultLat,resultLng);
var marker = new GMarker(point);
GEvent.addListener(marker, 'click', function() {
marker.openInfoWindowHtml(html);
});
map.addOverlay(marker);
bounds.extend(point);
if(geoCount == addresses.length) {
setCenterToBounds();
}
}else{
//console.info('Postcode not found!', address);
}
});
localSearch.execute(address + ', UK');
}
function placeMarkerAtPoint(point, html)
{
var marker = new GMarker(point,icon);
map.addOverlay(marker);
}
function setCenterToBounds()
{
map.setCenter(bounds.getCenter());
map.setZoom(map.getBoundsZoomLevel(bounds));
console.info('zoom',map.getBoundsZoomLevel(bounds));
}
function mapLoad() {
if (GBrowserIsCompatible()) {
map = new GMap2(document.getElementById('map'));
map.addControl(new GLargeMapControl());
map.addControl(new GMapTypeControl());
theNext();
}
}
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
oldonload();
func();
}
}
}
function addUnLoadEvent(func) {
var oldonunload = window.onunload;
if (typeof window.onunload != 'function') {
window.onunload = func;
} else {
window.onunload = function() {
oldonunload();
func();
}
}
}
addLoadEvent(mapLoad);
addUnLoadEvent(GUnload);
")
?>
It only happens on some of the markers though. It is like it finds the postcode, puts the marker on, but then displays the wrong details for it
Ok, so it seems that the data coming back from Google, seemed to come back in the wrong order.
Changing the var delay = 100 to var delay = 200 seemed to fix this
Even though it made the map load a little bit slower
I haven't worded this very well
But basically, I'd like to embed a map on my site - but the area it shows will change. I've tried doing this, but it never seems to work as it will focus on the wrong area - the old area, rather than the new area.
Basically, I'd like a google map code that uses $place as a location.
Thanks.
// Prepare your coordinates
var latlng1 = new google.maps.LatLng(0.0, 0.0);
var latlng2 = new google.maps.LatLng(100.0, 100.0);
// Initialize your map
var map = new google.maps.Map(document.getElementById('map'), options);
var options = {
zoom: 6,
center: latlng1,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
// Recenter the map/viewport
map.setCenter(latlng2);
If you don't have the location geocoded, you can look up by address like so: (assume you include your api key above this call - add in the lang vars to output value, in 2 places)
<script type="text/javascript">
$(document).ready(function() {
document.onunload = "GUnload()";
if (GBrowserIsCompatible()) {
var map = new GMap2(document.getElementById("map_canvas"));
map.setCenter(new GLatLng(0.0, 0.0), 13);
// map.setUIToDefault();
geocoder = new GClientGeocoder();
if (geocoder) {
geocoder.getLatLng( '$place', function(point) {
if (!point) {
} else {
var topRight = new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(10,10));var bottomRight = new GControlPosition (G_ANCHOR_BOTTOM_RIGHT, new GSize(10,10));
var mapTypeControl = new GMapTypeControl(); map.addControl(mapTypeControl, topRight);
map.addControl(new GSmallMapControl()); var bounds = map.getBounds();
map.setCenter(point, 13);
var marker = new GMarker(point);
map.addOverlay(marker);
GEvent.addListener(marker, 'click', function() { marker.openInfoWindowHtml('Get Directions ยป' );})
;}
}
);
}
// end geocoding
}
});
</script>