I can display all the markers from a request, but they point with a little gap in my map.
For instance, New York is pointed near Quebec. If I zoom into the map, all the markers move close to the right position.
Does anyone know how to fix it?
My code:
<script type="text/javascript" src="http://maps.google.com/maps/api/js?v=3.1&sensor=true"></script>
<script type="text/javascript">
//<![CDATA[
var geocoder;
var map;
var timeout = 600;
var address_position = 0;
var address = [
<?php
$_list="";
$_unicite=array();
foreach($search_data as $k => $item)
{
$_address=trim($item->meta_value);
if(!empty($_address))
{
if(!in_array($_address,$_unicite)){
$_unicite[$item->post_id]=$_address;
$_list.='"'.$_address.'",';
}
}
}
if(!empty($_list)) {
$_list=substr($_list,0,abs(strlen($_list)-1));
}
echo $_list;
?>
];
var link = [
<?php
$_list2="";
$_unicite2=array();
foreach($search_data as $k => $item)
{
$_link=trim($item->post_id);
if(!empty($_link))
{
if(!in_array($_link,$_unicite2)){
$_unicite2[$item->post_id]=$_link;
$_list2.='"'.$_link.'",';
}
}
}
if(!empty($_list2)) {
$_list2=substr($_list2,0,abs(strlen($_list2)-1));
}
echo $_list2;
?>
];
var title = [
<?php
$_list3="";
$_unicite3=array();
foreach($search_data as $k => $item)
{
$_title=trim($item->post_title);
if(!empty($_title))
{
if(!in_array($_title,$_unicite2)){
$_unicite2[$item->post_id]=$_title;
$_list3.='"'.$_title.'",';
}
}
}
if(!empty($_list3)) {
$_list3=substr($_list3,0,abs(strlen($_list3)-1));
}
echo $_list3;
?>
];
var image = new google.maps.MarkerImage(
'http://www.bookyourparis.com/images-site/beachflag.png',
new google.maps.Size(28,54),
new google.maps.Point(0,0),
new google.maps.Point(14,54)
);
function addMarker(position)
{
geocoder.geocode({'address': address[position]}, function(results, status)
{
address_position++;
if (address_position < address.length)
{
setTimeout(function() { addMarker(address_position); }, (timeout));
}
if (status == google.maps.GeocoderStatus.OVER_QUERY_LIMIT)
{
setTimeout(function() { addMarker(position); }, (timeout * 3));
}
/**
if (address_position < address.length)
{
if (status == google.maps.GeocoderStatus.OVER_QUERY_LIMIT)
{
setTimeout(function() { addMarker(position); }, (timeout * 3));
} else {
setTimeout(function() { addMarker(address_position); }, (timeout));
}
}
/**/
else if (status == google.maps.GeocoderStatus.OK)
{
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
position: results[0].geometry.location,
map: map,
title:address[position],
icon: image,
});
var contentString = '<div id="content_bulle"><div id="bodyContent_bulle" style="margin-top:5px;">'+
'<h1 style="font-size:1.5em">'+title[position]+
'</h1><h2 style="font-size:1.2em">'+results[0].formatted_address+
'</h2><p style="color:#AF1A40"><a target="_blank" href="?p='+link[position]+'">View</a></p>'+
'</div></div>';
var infowindow = new google.maps.InfoWindow({
content: contentString,
maxHeight: 100
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
}
});
}
function codeaddress() {
geocoder = new google.maps.Geocoder();
//var latlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions = {
zoom: 2,
navigationControlOptions: {style: google.maps.NavigationControlStyle.SMALL},
mapTypeId: google.maps.MapTypeId.HYBRID,
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
addMarker(address_position);
}
function centerMap()
{
map.setCenter(markers[markers.length-1].getPosition());
}
jQuery(window).load( function(){
codeaddress();
});
//]]>
</script>
<div id="map_canvas" style="width: 940px; height: 420px;border:1px solid #999"></div>
Related
How i show multiple location in google map in Codeigniter. I have one array including latitude and longitude. I want to show all the location in map.
This is my $query array passed from controller to view page,
Array (
[0] => stdClass Object ([lat] => 37.45360256419911 [lng] => -122.16470718383789)
[1] => stdClass Object ([lat] => 37.45455646705577 [lng] => -122.1653938293457)
[2] => stdClass Object ([lat] => 37.451543303913226 [lng] => -122.16745376586914)
)
i want to show all this 3 location in my map,now it's only marking 1 location.
<script>
var map;
var marker;
var infowindow;
var messagewindow;
function initMap() {
<?php
foreach($query as $row){
$lat=$row->lat;
$lng=$row->lng;
?>
var location = {lat: <?php echo $lat; ?>, lng: <?php echo $lng; ?>};
map = new google.maps.Map(document.getElementById('map'), {
center: location,
zoom: 13
});
var marker = new google.maps.Marker({
position: location,
map: map,
});
infowindow = new google.maps.InfoWindow({
content: document.getElementById('form')
});
messagewindow = new google.maps.InfoWindow({
content: document.getElementById('message')
});
google.maps.event.addListener(map, 'click', function(event) {
marker = new google.maps.Marker({
position: event.latLng,
map: map
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map, marker);
});
});
<?php
}
?>
}
It works fine for me...
In controller :
function latLanLocation()
{
if($this->session->userdata('logged_in'))
{
$session_data = $this->session->userdata('logged_in');
$data['title'] = 'Create client';
$ibo = $this->session->userdata['logged_in']['ibo'];
$latLanQuery = $this->db->query('select name,latitude,longitude from distributor_clients where sponsor='.$ibo.' AND status="A" AND latitude !=0 AND longitude !=0');
$userData = $latLanQuery->result_array();
$locations='[';
foreach ($userData as $key => $row) {
$name = $row['name'];
$longitude = $row['longitude'];
$latitude = $row['latitude'];
$locations .= '["'.$name.'","'.$latitude.'","'.$longitude.'"],';
}
$locations .= ']';
$data['markers'] = $locations;
$this->load->view('location', $data);
}
else
{
redirect('login', 'refresh');
}
}
//In View folder create location.php
// Html code for Google Map Javascript API
<!DOCTYPE html>
<html>
<head>
<style>
#mapCanvas {
height: 400px;
width: 100%;
}
</style>
</head>
<body>
<div id="mapCanvas"></div>
<script>
function initMap() {
var map;
var bounds = new google.maps.LatLngBounds();
var mapOptions = {
mapTypeId: 'roadmap'
};
map = new google.maps.Map(document.getElementById("mapCanvas"), mapOptions);
map.setTilt(50);
var markers = <?php echo $markers; ?>
// Add multiple markers to map
var infoWindow = new google.maps.InfoWindow(), marker, i;
// Place each marker on the map
for( i = 0; i < markers.length; i++ ) {
var position = new google.maps.LatLng(markers[i][1], markers[i][2]);
bounds.extend(position);
marker = new google.maps.Marker({
position: position,
map: map,
title: markers[i][0]
});
// Center the map to fit all markers on the screen
map.fitBounds(bounds);
}
// Set zoom level
var boundsListener = google.maps.event.addListener((map), 'bounds_changed', function(event) {
this.setZoom(14);
google.maps.event.removeListener(boundsListener);
});
}
// Load initialize function
google.maps.event.addDomListener(window, 'load', initMap);
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=API_KEY&callback=initMap"></script>
</body>
</html>
The final output:
Not tested but you could try like this. Put the php code before and generate an array of lat,lng coordinates which you convert to json for use by the initmap function. Iterate through the object members and add a new marker.
<?php
$data=array();
foreach($query as $row){
$lat=$row->lat;
$lng=$row->lng;
$data[]=array('lat'=>$lat,'lng'=>$lng);
}
$json=json_encode( $data );
?>
<script>
var map;
var marker;
var infowindow;
var messagewindow;
<?php
echo "
var json={$json};
var lat={$lat};
var lng={$lng};
"
?>
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: location,
zoom: 13
});
infowindow = new google.maps.InfoWindow({
content: document.getElementById('form')
});
messagewindow = new google.maps.InfoWindow({
content: document.getElementById('message')
});
google.maps.event.addListener( map, 'click', function(event) {
marker = new google.maps.Marker({
position: event.latLng,
map: map
});
});
for( var n in json ){
var obj=json[ n ];
lat=obj.lat;
lng=obj.lng;
var location = { lat:lat, lng:lng };
var marker = new google.maps.Marker({
position: location,
map: map,
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map, marker);
});
}
}
</script>
Using the key you provided in the comment I get an error about an invalid key and the map refuses to load at all. Using a different key however worked fine with a couple of alterations.
My db connection is mysqli and the query and processing of recordset may or may not be the same method you chose. You need to edit this according to your needs as those details were ommited from the question.
<?php
/* emulated db connection */
include __DIR__. '/db.php';
/* get markers from a table */
$sql='select `name`,`lat`,`lng` from markers limit 20';
$result=$db->query( $sql );
?>
<!--
Original question:
https://stackoverflow.com/questions/48437784/how-i-show-multiple-location-in-google-map-codeigniter/48438084?noredirect=1#comment83871602_48438084
-->
<?php
/* generate data array & convert to json */
$data=array();
/*
foreach( $query as $row ){
}
*/
while( $row=$result->fetch_object() ){
$lat=$row->lat;
$lng=$row->lng;
$name=$row->name;
$data[]=array('name'=>$name,'lat'=>$lat,'lng'=>$lng);
}
$json=json_encode( $data );
?>
<!doctype html>
<html>
<head>
<meta charset='utf-8' />
<title>Google maps - display markers</title>
<script>
var map;
var marker;
var infowindow;
var messagewindow;
<?php
echo "
var json={$json};
var lat={$lat};
var lng={$lng};
"
?>
function initMap() {
var location=new google.maps.LatLng( lat,lng );
map = new google.maps.Map( document.getElementById('map'), {
center: location,
zoom: 13
});
infowindow = new google.maps.InfoWindow({
content: document.getElementById('form')
});
messagewindow = new google.maps.InfoWindow({
content: document.getElementById('message')
});
google.maps.event.addListener( map, 'click', function(event) {
marker = new google.maps.Marker({
position: event.latLng,
map: map
});
});
for( var n in json ){
var obj=json[ n ];
lat=obj.lat;
lng=obj.lng;
name=obj.name;
var location = new google.maps.LatLng( lat, lng );
var marker = new google.maps.Marker({
position: location,
title:name,
map: map,
});
google.maps.event.addListener( marker, 'click', function() {
var content=infowindow.getContent();
content.querySelector('input[name="lat"]').value=e.latLng.lat();
content.querySelector('input[name="lng"]').value=e.latLng.lng();
content.querySelector('input[name="name"]').value=this.title;
infowindow.open( map, this );
}.bind( marker )); /* bind to THIS marker */
}
}
</script>
<script async defer src='//maps.googleapis.com/maps/api/js?key=<API KEY>&callback=initMap'></script>
<style>
#map{
width:800px;
height:600px;
float:none;
margin:auto;
}
</style>
</head>
<body>
<div id='map'></div>
<form id='form'>
<input type='text' name='lat' />
<input type='text' name='lng' />
<input type='submit' />
</form>
<div id='message'>unknown content</div>
</body>
</html>
This code can display multi different markers. Hope this help you.
<!DOCTYPE html>
<html>
<head>
<title>Custom Markers</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 16,
center: new google.maps.LatLng(-33.91722, 151.23064),
mapTypeId: 'roadmap'
});
var iconBase = 'https://maps.google.com/mapfiles/kml/shapes/';
var icons = {
library: {
icon: iconBase + 'library_maps.png'
},
info: {
icon: iconBase + 'info-i_maps.png'
}
};
var features = [
// do looping here and replace LatLng value using foreach PHP.
{
position: new google.maps.LatLng(-33.91721, 151.22630),
type: 'info'
}, {
position: new google.maps.LatLng(-33.91539, 151.22820),
type: 'library'
},
];
// Create markers.
features.forEach(function(feature) {
var marker = new google.maps.Marker({
position: feature.position,
icon: icons[feature.type].icon,
map: map
});
});
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
</script>
</body>
</html>
source : https://developers.google.com/maps/documentation/javascript/custom-markers
to put map in my site i follow one example and it will display static markers like.
var locations = [
['Bondi Beach', -33.890542, 151.274856],
['Coogee Beach', -33.923036, 151.259052],
['Cronulla Beach', -34.028249, 151.157507],
['Manly Beach', -33.80010128657071, 151.28747820854187],
['Maroubra Beach', -33.950198, 151.259302]
];
i want it dynamic from mysql table. it has lat and lng. i tried this but not working
<?php
$host = "localhost";
$db_name = "aarya";
$user = "root";
$password = "";
$con = mysql_connect($host,$user,$password) or die("connection error");
mysql_select_db($db_name) or die("could't connect to database");
$query="SELECT * FROM detail";
$result=mysql_query($query);
while ($row=mysql_fetch_array($result)) {
?>
var locations = [
['<?php echo $row['name'];?>','<?php echo $row['lat'];?>','<?php echo $row['lng'];?>'],
<?php
}
?>
];
i think problem in locations array and i am new in google maps please help me.
Here is a rough example of doing this:
Your locations array:
<?php
$locations[0] = array("lat"=>"-33.890542", "long"=>"151.274856", "info" => "Bondi Beach");
$locations[1] = array("lat"=>"-33.923036", "long"=>"151.259052", "info" => "Coogee Beach");
$locations[2] = array("lat"=>"-34.028249", "long"=>"151.157507", "info" => "Cronulla Beach");
$locations[3] = array("lat"=>"-33.80010128657071", "long"=>"151.28747820854187", "info" => "Manly Beach");
$locations[4] = array("lat"=>"-33.950198", "long"=>"151.259302", "info" => "Maroubra Beach");
?>
Or you could query the database like:
<?php
$query="SELECT * FROM detail";
$result=mysql_query($query);
while ($row=mysql_fetch_array($result)) {
$locations[] = array("lat"=>$row['lat'], "long"=>$row['lng'], "info" => $row['name']);
}
?>
You can modify the above array with the values from your database.
The map:
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<style type="text/css">
body { font: normal 10pt Helvetica, Arial; }
#map { width: 350px; height: 300px; border: 0px; padding: 0px; }
</style>
<script src="http://maps.google.com/maps/api/js?v=3&sensor=false" type="text/javascript"></script>
<script type="text/javascript">
var icon = new google.maps.MarkerImage("http://maps.google.com/mapfiles/ms/micons/blue.png",
new google.maps.Size(32, 32), new google.maps.Point(0, 0),
new google.maps.Point(16, 32));
var center = null;
var map = null;
var currentPopup;
var bounds = new google.maps.LatLngBounds();
function addMarker(lat, lng, info)
{
var pt = new google.maps.LatLng(lat, lng);
bounds.extend(pt);
var marker = new google.maps.Marker(
{
position: pt,
icon: icon,
map: map
});
var popup = new google.maps.InfoWindow(
{
content: info,
maxWidth: 300
});
google.maps.event.addListener(marker, "click", function()
{
if (currentPopup != null)
{
currentPopup.close();
currentPopup = null;
}
popup.open(map, marker);
currentPopup = popup;
});
google.maps.event.addListener(popup, "closeclick", function()
{
map.panTo(center);
currentPopup = null;
});
}
function initMap()
{
map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(0, 0),
zoom: 0,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false,
mapTypeControlOptions:
{
style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR
},
navigationControl: true,
navigationControlOptions:
{
style: google.maps.NavigationControlStyle.SMALL
}
});
<?php foreach($locations AS $loc) { //you could replace this with your while loop query ?>
addMarker(<?php echo $loc["lat"]; ?>, <?php echo $loc["long"]; ?>, '<?php echo $loc["info"]; ?>');
<?php } ?>
center = bounds.getCenter();
map.fitBounds(bounds);
}
</script>
</head>
<body onload="initMap()" style="margin:0px; border:0px; padding:0px;">
<div id="map"></div>
</html>
Hope that helps :)
You are initialising var locations everytime your while loop is running . In that aspect you will have the value of only the last iteration.Please initialise locations outside and push the values inside the javascript array.Also you should consider json_encode way .It is much cleaner.
if you new at google maps you can use gmaps.js it allows you to use the potential of Google Maps in a simple way.
https://hpneo.github.io/gmaps/
and its marker example:
https://hpneo.github.io/gmaps/examples/markers.html
I think you need to use objects:
var locations = {
{
title: '<?= $row['name'] ?>',
lat: '<?= $row['lat'] ?>',
lng: '<?= $row['lng'] ?>'
}
}
And you can use json_encode instead
In your code you already have following locations available globally:
var locations = [
['Bondi Beach', -33.890542, 151.274856],
['Coogee Beach', -33.923036, 151.259052],
['Cronulla Beach', -34.028249, 151.157507],
['Manly Beach', -33.80010128657071, 151.28747820854187],
['Maroubra Beach', -33.950198, 151.259302]
];
Now add the following HTML and Javascript in your file and refresh the page. This will show you the Google map.
HTML:
<div id="map_canvas" style="width:700px;height:500px;"></div>;
Javascript
function loadMap()
{
var map;
var bounds = new google.maps.LatLngBounds();
var mapOptions = {
mapTypeId: 'roadmap'
};
// Display a map on the page
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
for( i = 0; i < locations.length; i++ ) {
var loc = locations[i];
var position = new google.maps.LatLng(loc[1], loc[2]);
bounds.extend(position);
marker = new google.maps.Marker({
position: position,
map: map,
title: loc[0]
});
map.fitBounds(bounds);
}
}
google.maps.event.addDomListener(window, 'load', loadMap);
If you want to dynamically use your database please check this example.
Create the file map3.php. File same as here
$conn = mysql_connect("localhost","root","");
mysql_select_db('yourdatabase');
function parseToXML($htmlStr)
{
$xmlStr=str_replace('<','<',$htmlStr);
$xmlStr=str_replace('>','>',$xmlStr);
$xmlStr=str_replace('"','"',$xmlStr);
$xmlStr=str_replace("'",''',$xmlStr);
$xmlStr=str_replace("&",'&',$xmlStr);
return $xmlStr;
}
$query = mysql_query("select * from yourtable");
//header("Content-type: text/html");
/* Get lat and Lan using table query */
$i=0;
while($row = mysql_fetch_assoc($query)){
$reposnse['markers'][$i]['lat']= $row['lat'];
$reposnse['markers'][$i]['lag']= $row['lag'];
$i++;
}
echo json_encode($reposnse);
?>
After create map2.php same as here
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="http://maps.google.com/maps/api/js?sensor=false" type="text/javascript"></script>
<script type="application/javascript">
$(document).ready(function(e) {
$.ajax({
url:"map3.php",
dataType: 'json',
success: function(result){
var html = '<markers>';
for (var prop in result['markers']) {
var value = result['markers'][prop];
//alert(value.lat);
html += '<marker ';
html += 'lat="';
html += value.lat+'"';
html += 'lng="';
html += value.lag+'"';
html += '/>';
}
html += '</markers>';
$('#test').html(html);
function initialize() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 6,
center: new google.maps.LatLng(15.317277,75.71389),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var marker;
var location = {};
var markers = document.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
//alert(markers[i].getAttribute("lat"));
location = {
name : 'test'+i,
address : 'baglore',
city : 'bangalore',
state : 'Karnataka',
zip : '560017',
pointlat : parseFloat(markers[i].getAttribute("lat")),
pointlng : parseFloat(markers[i].getAttribute("lng"))
};
console.log(location);
marker = new google.maps.Marker({
position: new google.maps.LatLng(location.pointlat, location.pointlng),
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker,location) {
return function() {
infowindow.setContent(location.name);
infowindow.open(map, marker);
};
})(marker, location));
}
}
google.maps.event.addDomListener(window, 'load', initialize);
},
});
});
</script>
</head>
<body>
<div id="test">
</div>
<div id="map" style="width: 500px; height: 400px;"></div>
</body>
</html>
Please check the link below Adding multiple markers to google maps using javascript and php
I must adjust a website, but I don't understand this function:
var geocoder;
var map;
var markersArray = [];
var bounds;
var infowindow;
var appena_entrato = true;
var mappa_attiva = "tt";
-- Initialize_map
function initialize_map() {
markersArray = [];
var myLatlng = new google.maps.LatLng(45.6841895,11.4775636);
var myOptions = {
zoom: 14,
maxZoom: 18,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
scrollwheel: false,
disableDoubleClickZoom: true,
mapTypeControl: false,
panControl: true,
panControlOptions: {
position: google.maps.ControlPosition.TOP_RIGHT
},
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.LARGE,
position: google.maps.ControlPosition.RIGHT_TOP
},
scaleControl: false,
streetViewControl: false
}
geocoder = new google.maps.Geocoder();
map = new google.maps.Map(document.getElementById("map-canvas-"+mappa_attiva), myOptions);
var marker = new google.maps.Marker({
position: new google.maps.LatLng(45.6841895,11.4775636),
map: map,
title:"COMPANY NAME"
});
marker.setMap(map);
var contentString = '<div>'+
'<h2>COMPANY NAME</h2>'+
'<div style="width:400px;">'+
'<p>ADDRESS<br>' +
'Ph. +39 0000- Fax. +39 00000</p>'+
'</div>'+
'</div>';
marker.infowindow = new google.maps.InfoWindow({
content: contentString
});
google.maps.event.addListener(marker, 'click', function() {
marker.infowindow.open(map,marker);
});
markersArray.push(marker);
for (i in markersArray) {
markersArray[i].infowindow.open(map,markersArray[i]);
}
getLocation();
}
-- GetLocation
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
//console.log("Geolocation not supported!");
}
}
-- ShowPosition
function showPosition(position) {
var myLatlng = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
map.setCenter(myLatlng);
map.setZoom(9);
coordsAddress(position.coords.latitude,position.coords.longitude,function(results){
for (var i=0; i<results.length; i++) {
for (var b=0; b<results[i].types.length; b++) {
if (results[i].types[b] == "administrative_area_level_2") {
var indice = i;
}
}
}
for (var i=0; i<results[indice].address_components.length; i++) {
for (var b=0; b<results[indice].address_components[i].types.length; b++) {
if (results[indice].address_components[i].types[b] == "administrative_area_level_2") {
var postalCode = results[indice].address_components[i].short_name;
}
}
}
$("#provincia option:selected").removeAttr("selected");
$("#provincia option[value="+postalCode+"]").prop("selected",true);
mostra_coords(position.coords.latitude, position.coords.longitude, 50);
});
}
-- Code Address
function codeAddress(zipCode,country,callback) {
geocoder.geocode({address: zipCode, region: country}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
callback(results);
} else {
alert('No results found');
}
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
-- CoordsAddress
function coordsAddress(latitude,longitude,callback) {
var myLatlng = new google.maps.LatLng(latitude,longitude);
geocoder.geocode({'latLng': myLatlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
callback(results);
} else {
alert('No results found');
}
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
--Add marker
function add_spillo(indirizzo) {
var id = indirizzo.attr("id");
var geo = indirizzo.attr("rel");
var text = indirizzo.parent().html();
var icona = 'img/point.png';
indirizzo = geo.split(",");
var myLatlng = new google.maps.LatLng(indirizzo[0],indirizzo[1]);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
icon: icona
});
marker.infowindow = new google.maps.InfoWindow({
content: text
});
google.maps.event.addListener(marker, 'click', function () {
marker.infowindow.open(map, marker);
});
markersArray.push(marker);
bounds.extend(myLatlng);
}
-- Map centre
function centra_mappa(coords) {
var lat = coords.lat();
var lon = coords.lng();
var max_lon = map.getBounds().getNorthEast().lng();
var max_lat = map.getBounds().getNorthEast().lat();
var min_lon = map.getBounds().getSouthWest().lng();
var min_lat = map.getBounds().getSouthWest().lat();
max_lon = Math.max(lon, max_lon);
min_lon = Math.min(lon, min_lon);
max_lat = Math.max(lat, max_lat);
min_lat = Math.min(lat, min_lat);
var ne = new google.maps.LatLng(max_lat, max_lon);
var sw = new google.maps.LatLng(min_lat, min_lon);
var nuovi_bordi = new google.maps.LatLngBounds(sw, ne);
map.fitBounds(nuovi_bordi);
}
-- Delete Overlays
function deleteOverlays() {
if (markersArray) {
for (i in markersArray) {
markersArray[i].infowindow.close();
markersArray[i].setMap(null);
}
markersArray.length = 0;
}
}
-- Coords Show
function mostra_coords(lat, lng, distance) {
customurl = "../ajax/negozi.php";
$("#boxNegozi-"+mappa_attiva+" ul").load(customurl, {
lat: lat,
lng: lng,
distance: distance,
brand: mappa_attiva
}, function(data) {
if (data == "") return alert("No shops found on your search1");
deleteOverlays();
bounds = new google.maps.LatLngBounds();
$(data).find("input").each(function(index, element) {
add_spillo($(this));
});
map.fitBounds(bounds);
appena_entrato = false;
});
}
-- Provincia Show
function mostra(provincia) {
customurl = "../ajax/negozi.php";
$("#boxNegozi-"+mappa_attiva+" ul").load(customurl, {
provincia: provincia,
brand: mappa_attiva
}, function(data) {
if (data == "") return alert("No shops found on your search2");
deleteOverlays();
bounds = new google.maps.LatLngBounds();
$(data).find("input").each(function(index, element) {
add_spillo($(this));
});
map.fitBounds(bounds);
});
}
--Nazione Show
function mostra_nazione(nazione) {
customurl = "../ajax/negozi.php";
$("#boxNegozi-"+mappa_attiva+" ul").load(customurl, {
country: nazione,
brand: mappa_attiva
}, function(data) {
if (data == "") return alert("No shops found on your search3");
deleteOverlays();
bounds = new google.maps.LatLngBounds();
$(data).find("input").each(function(index, element) {
add_spillo($(this));
});
map.fitBounds(bounds);
});
}
google.maps.event.addDomListener(window, 'load', initialize_map);
$(document).ready(function(){
$("#provincia-ttt").change(function(){
var provincia = $(this).val();
mostra(provincia);
});
$("#provincia-tt").change(function(){
var provincia = $(this).val();
mostra(provincia);
});
$("#nazione-ttt").change(function(){
console.log($(this).val());
if ($(this).val() == "IT") $("#teen_provincia").show();
else {
$("#teen_provincia").hide();
mostra_nazione($(this).val());
}
});
$('#tabs a').click(function (e) {
e.preventDefault();
$(this).tab('show');
if ($(this).attr('href') == "#orange") {
mappa_attiva = "ttt";
} else {
mappa_attiva = "tt";
}
initialize_map();
$("#provincia-"+mappa_attiva).val("");
$("#boxNegozi-"+mappa_attiva+" ul").html("");
});
});
-- I MADE THIS PHP PAGE BUT DON'T WORK, WHERE I MAKE ERROR? thanks in advance
<?
$dbname ='ltaketwd_db'; //Name of the database
$dbuser ='ltaketwd_admin'; //Username for the db
$dbpass ='Twork.01'; //Password for the db
$dbserver ='localhost'; //Name of the mysql server
$dbcnx = mysql_connect ("$dbserver", "$dbuser", "$dbpass");
mysql_select_db("$dbname") or die(mysql_error());
$query = mysql_query("SELECT * FROM negozi");
while ($row = mysql_fetch_array($query)){
$lat=$row['lat'];
$lng=$row['lng'];
$distance=$row['distance'];
$name=$row['name'];
$indirizzo=$row['indirizzo'];
$provincia=$row['provincia'];
$nazione=$row['nazione'];
}
?>
AJAX = Asynchronous JavaScript and XML.
In short; AJAX allows you to load data in the background, manipulate it and display it on the webpage, without needing a page reload.
Have a look at jQuery's documentation for load().
You'll see that load() takes up to three parameters, which is what happens here :
$("#boxStore-"+active_map+" ul") // the element you want as container for your document
.load(
customurl, // 1) the page/document you want to load in the container
{lat:lat, ..... }, // 2) variables you pass to the page so it generates differently
function(data) {
/* 3) callback function, that will be executed after load() is finished. "data" is the page/document you called. */
}
);
I'm trying to place multiple markers on a map. For this, I followed this procedure
https://developers.google.com/maps/documentation/javascript/examples/places-autocomplete?csw=1
Demo
But here, once user starts typing for another marker, then first marker is getting replaced by the second marker. For this, I initialized the marker inside autocomplete function so that it creates another marker as user enters second one. This worked fine. Another marker is getting pinned. But onclicking the marker, it will not produce infowindow since the infowindow is inside autocomplete function.
I need infowindow for all markers.
<script>
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(-33.8688, 151.2195),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
var input = /** #type {HTMLInputElement} */(document.getElementById('searchTextField'));
var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.bindTo('bounds', map);
var infowindow = new google.maps.InfoWindow();
google.maps.event.addListener(autocomplete, 'place_changed', function() {
var marker = new google.maps.Marker({
map: map
});
infowindow.close();
marker.setVisible(false);
input.className = '';
var place = autocomplete.getPlace();
if (!place.geometry) {
// Inform the user that the place was not found and return.
input.className = 'notfound';
return;
}
// If the place has a geometry, then present it on a map.
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(17); // Why 17? Because it looks good.
}
var address = '';
if (place.address_components) {
address = [
(place.address_components[0] && place.address_components[0].short_name || ''),
(place.address_components[1] && place.address_components[1].short_name || ''),
(place.address_components[2] && place.address_components[2].short_name || '')
].join(' ');
}
marker.setIcon(/** #type {google.maps.Icon} */({
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(35, 35),
}));
if (address.length != 0) {
address = place.name + ', ' + address;
} else {
address = place.name;
}
marker.setPosition(place.geometry.location);
marker.setTitle(address);
marker.setVisible(true);
infowindow.setContent('<div><strong>' + marker.title + '</strong><br>');
infowindow.open(map, marker);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
Here infowindow will not work since there is no action listener for this. so I wrote the below code.
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map, marker);
});
But it wont work as marker is out of scope variable here. How to do this? Please help
Use a createMarker function to hold function closure on the infowindow content.
<script type="text/javascript">
var map = null;
var infowindow = new google.maps.InfoWindow();
function createMarker(place) {
var marker = new google.maps.Marker({
map: map
});
// If the place has a geometry, then present it on a map.
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(17); // Why 17? Because it looks good.
}
var address = '';
if (place.address_components) {
address = [
(place.address_components[0] && place.address_components[0].short_name || ''),
(place.address_components[1] && place.address_components[1].short_name || ''),
(place.address_components[2] && place.address_components[2].short_name || '')
].join(' ');
}
marker.setIcon(/** #type {google.maps.Icon} */({
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(35, 35),
}));
if (address.length != 0) {
address = place.name + ', ' + address;
} else {
address = place.name;
}
marker.setPosition(place.geometry.location);
marker.setTitle(address);
marker.setVisible(true);
google.maps.event.addListener(marker, 'click', function(e) {
infowindow.setContent('<div><strong>' + marker.title + '</strong><br>');
infowindow.open(map, marker);
});
google.maps.event.trigger(marker, 'click');
}
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(-33.8688, 151.2195),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
var input = /** #type {HTMLInputElement} */(document.getElementById('searchTextField'));
var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.bindTo('bounds', map);
google.maps.event.addListener(autocomplete, 'place_changed', function() {
infowindow.close();
input.className = '';
var place = autocomplete.getPlace();
if (!place.geometry) {
// Inform the user that the place was not found and return.
input.className = 'notfound';
return;
}
createMarker(place);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
working example
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