I'm working on an app with few points of coordinates but I can't get the center points. Can anyone help? this is my code:
<div id="mymap"></div>
<script type="text/javascript">
function initMap() {
var locations = <?php print_r(json_encode($hospitalmap)) ?>;
var mymap = new GMaps({
el: '#mymap',
lat: mymap.getCenter().lat(),
lng: mymap.getCenter().lng(),
zoom:13
});
//gMap.setCenter(new google.maps.LatLng(-6.2598513, 106.6160752));
$.each( locations, function( index, value ){
mymap.addMarker({
lat: value.HospitalLatitude,
lng: value.HospitalLongitude,
title: value.HospitalName,
click: function(e) {
alert('This is '+value.HospitalName+'.');
}
});
});
}
</script>
PS it works if i sent the center manually
EDIT: I tried to change it with rohit's guide to this
var bounds = new google.maps.LatLngBounds();
var mymap = new GMaps({
el: '#mymap',
zoom:13
});
$.each( locations, function( index, value ){
mymap.addMarker({
lat: value.HospitalLatitude,
lng: value.HospitalLongitude,
title: value.HospitalName,
click: function(e) {
alert('This is '+value.HospitalName+'.');
}
});
bounds.extend(marker.position);
}
);map.fitBounds(bounds);
}
</script>
still not working at the moment. Please help!
Heres the data sample:
var locations = [
{"HospitalID":2,"HospitalName":"RS Bethsaida","HospitalDesc":"","HospitalClass":"A","HospitalAddress":"Curug Sangereng, Kelapa Dua, Tangerang, Banten","HospitalPhone":"02183929302","HospitalEmail":"bethsaida#gmail.com","HospitalLatitude":"-6.254463","HospitalLongitude":"106.622776","Balance":"5250007","Active":"1","LoginMethod":null,"AcceptedBy":null,"AcceptedDate":null,"CreatedBy":"5","CreatedDate":"2017-08-01 00:00:00","ModifiedBy":"5","ModifiedDate":"2017-08-03 00:00:00"},
{"HospitalID":3,"HospitalName":"RS Mayapada","HospitalDesc":"","HospitalClass":"A","HospitalAddress":"Modernland, Jl. Honoris Raya Kav. 6, Kelapa Indah, Klp. Indah, Kec. Tangerang, Kota Tangerang, Banten","HospitalPhone":"02100001920","HospitalEmail":"rs#mayapada.com","HospitalLatitude":"-6.204981","HospitalLongitude":"106.641538","Balance":"0","Active":"1","LoginMethod":null,"AcceptedBy":null,"AcceptedDate":null,"CreatedBy":"5","CreatedDate":"2017-08-01 00:00:00","ModifiedBy":"5","ModifiedDate":"2017-08-03 00:00:00"}];
Now the below is a working sample, you can replace the locations by your PHP code, and hope this works well.
<script type='text/javascript' src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type='text/javascript' src="https://maps.google.com/maps/api/js?key=AIzaSyD95RyzZ5IEngrkYckzqRMAwyCZ7-eezMw"></script>
<script type='text/javascript' src="https://cdnjs.cloudflare.com/ajax/libs/gmaps.js/0.4.24/gmaps.js"></script>
<div id="map">dfas</div>
<style>
#map {
width: 98%;
height: 600px;
margin-bottom:50px;
margin-left:15px;
}
</style>
<script type='text/javascript'>
function initMap() {
var locations = [
{"HospitalID":2,"HospitalName":"RS Bethsaida","HospitalDesc":"","HospitalClass":"A","HospitalAddress":"Curug Sangereng, Kelapa Dua, Tangerang, Banten","HospitalPhone":"02183929302","HospitalEmail":"bethsaida#gmail.com","HospitalLatitude":"-6.254463","HospitalLongitude":"106.622776","Balance":"5250007","Active":"1","LoginMethod":null,"AcceptedBy":null,"AcceptedDate":null,"CreatedBy":"5","CreatedDate":"2017-08-01 00:00:00","ModifiedBy":"5","ModifiedDate":"2017-08-03 00:00:00"},
{"HospitalID":3,"HospitalName":"RS Mayapada","HospitalDesc":"","HospitalClass":"A","HospitalAddress":"Modernland, Jl. Honoris Raya Kav. 6, Kelapa Indah, Klp. Indah, Kec. Tangerang, Kota Tangerang, Banten","HospitalPhone":"02100001920","HospitalEmail":"rs#mayapada.com","HospitalLatitude":"-6.204981","HospitalLongitude":"106.641538","Balance":"0","Active":"1","LoginMethod":null,"AcceptedBy":null,"AcceptedDate":null,"CreatedBy":"5","CreatedDate":"2017-08-01 00:00:00","ModifiedBy":"5","ModifiedDate":"2017-08-03 00:00:00"}];
var map;
var bounds = new google.maps.LatLngBounds();
map = new GMaps({
el: '#map',
lat: -6.254463,
lng: 106.622776
});
$.each( locations, function( index, value ){
map.addMarker({
lat: parseFloat(value.HospitalLatitude),
lng: parseFloat(value.HospitalLongitude),
title: value.HospitalName,
click: function(e) {
alert('This is '+value.HospitalName+'.');
}
});
bounds.extend({lat: parseFloat(value.HospitalLatitude), lng: parseFloat(value.HospitalLongitude)});
});
map.fitBounds(bounds);
}
initMap();
</script>
Thanks
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 have this script that will show custom markers on a google map, but I would like to include a input text-box and be able to enter a city/state and a zip-code and see if there are any markers within lets say 400 miles from that city/state or zip-code. I would love it if the map can be dynamic so as you type out the city/state or zip-code it will show the results on the map by getting rid of all the other markers and leaving only the one that is within that radius, if that is too hard then a simple alter box saying what unit is the closest will also be OK :) I searched and found some say that I should load the geometry library and use computeDistanceBetween() to find the distance of each marker from your center point but I have no idea how to do the zip-code part or how to put all of this together to work.
Here is my code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title></title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclustererplus/src/markerclusterer.js"></script>
<script type="text/javascript">
var image = new google.maps.MarkerImage("marker-images/image.png",new google.maps.Size(40,35),new google.maps.Point(0,0),new google.maps.Point(20,35));
var shadow = new google.maps.MarkerImage(
'marker-images/shadow.png',
new google.maps.Size(62,35),
new google.maps.Point(0,0),
new google.maps.Point(20,35)
);
var shape = {
coord: [27,0,30,1,32,2,34,3,35,4,36,5,38,6,39,7,39,8,39,9,39,10,38,11,37,12,33,13,34,14,34,15,33,16,32,17,31,18,27,19,28,20,28,21,27,22,26,23,22,25,23,26,24,27,24,28,24,29,24,30,24,31,24,32,23,33,22,34,17,34,16,33,15,32,15,31,14,30,14,29,15,28,15,27,16,26,17,25,13,23,12,22,11,21,11,20,12,19,8,18,7,17,6,16,5,15,5,14,6,13,2,12,1,11,0,10,0,9,0,8,0,7,1,6,3,5,4,4,5,3,7,2,9,1,12,0,27,0],
type: 'poly'
};
// this variable will collect the html which will eventually be placed in the side_bar
var side_bar_html = "";
// arrays to hold copies of the markers and html used by the side_bar
// because the function closure trick doesnt work there
var gmarkers = [];
// global "map" variable
var map = null;
var circle = null;
//marker clusterer
var mc;
var mcOptions = {gridSize: 10, maxZoom: 8};
//global infowindow
var infowindow = new google.maps.InfoWindow();
//geocoder
var geocoder = new google.maps.Geocoder();
var address = new Array("41.8119,-87.6873",
"40.7888,-74.056",
"41.8119,-87.6873",
"48.6681,-97.3627",
"44.9793,-93.273",
"39.4857,-75.6775",
"41.8119,-87.6873",
"42.0203,-87.9059",
"32.7812,-96.7903",
"27.5159,-99.4941",
"32.7812,-96.7903",
"37.5608,-95.6684",
"41.8119,-87.6873",
"38.3763,-97.6702",
"42.2458,-83.2491",
"41.8122,-91.9139",
"41.8397,-88.0887",
"41.8397,-88.0887",
"38.5128,-122.787",
"41.8397,-88.0887",
"42.8863,-87.892",
"42.8863,-87.892",
"30.7539,-83.3321",
"39.889,-84.2422",
"34.106,-83.589");
var content = new Array("Unit No# 0206",
"Unit No# #2003",
"Unit No# 0176",
"Unit No# #2001",
"Unit No# 0124",
"Unit No# 0157",
"Unit No# #0162",
"Unit No# 0104",
"Unit No# 0118",
"Unit No# #2007",
"Unit No# 0112",
"Unit No# 0139",
"Unit No# 0205",
"Unit No# 0127",
"Unit No# 0187",
"Unit No# 0105",
"Unit No# 0214",
"Unit No# 0186",
"Unit No# 0173",
"Unit No# 0134",
"Unit No# 0128",
"Unit No# 0125",
"Unit No# 0158",
"Unit No# 0193",
"Unit No# 0201");
//min and max limits for multiplier, for random numbers
//keep the range pretty small, so markers are kept close by
var min = .999999;
var max = 1.000001;
function createMarker(latlng,text) {
var marker = new google.maps.Marker({
draggable: false,
raiseOnDrag: false,
icon: image,
shadow: shadow,
shape: shape,
position: latlng,
map: map
});
///get array of markers currently in cluster
var allMarkers = mc.getMarkers();
//check to see if any of the existing markers match the latlng of the new marker
if (allMarkers.length != 0) {
for (i=0; i < allMarkers.length; i++) {
var existingMarker = allMarkers[i];
var pos = existingMarker.getPosition();
if (latlng.equals(pos)) {
text = text + " & " + content[i];
}
}
}
google.maps.event.addListener(marker, 'click', function() {
infowindow.close();
infowindow.setContent(text);
infowindow.open(map,marker);
});
mc.addMarker(marker);
return marker;
}
function initialize(){
var options = {
zoom: 4,
center: new google.maps.LatLng(39.8282,-98.5795),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map'), options);
//marker cluster
var gmarkers = [];
mc = new MarkerClusterer(map, [], mcOptions);
for (i=0; i<address.length; i++) {
var ptStr = address[i];
var coords = ptStr.split(",");
var latlng = new google.maps.LatLng(parseFloat(coords[0]),parseFloat(coords[1]));
gmarkers.push(createMarker(latlng,content[i]));
}
}
function codeAddress() {
var address = document.getElementById('address').value;
var radius = parseInt(document.getElementById('radius').value, 10) * 1609.34;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
// map: map, <-- uncomment to show red marker
position: results[0].geometry.location
});
if (circle) circle.setMap(null);
circle = new google.maps.Circle({center:marker.getPosition(),
radius: radius,
fillOpacity: 0.35,
fillColor: "#FF0000",
map: map});
var bounds = new google.maps.LatLngBounds();
var foundMarkers = 0;
for (var i=0; i<gmarkers.length;i++) {
if (google.maps.geometry.spherical.computeDistanceBetween(gmarkers[i].getPosition(),marker.getPosition()) < radius) {
bounds.extend(gmarkers[i].getPosition())
gmarkers[i].setMap(map);
foundMarkers++;
} else {
gmarkers[i].setMap(null);
}
}
if (foundMarkers > 0) {
map.fitBounds(bounds);
} else {
map.fitBounds(circle.getBounds());
}
} else {
alert(status);
}
});
}
var infowindow = new google.maps.InfoWindow(
{
size: new google.maps.Size(150,50)
});
function handleKeyPress(e){
var key=e.keyCode || e.which;
if (key==13){
codeAddress();
}
}
function handleResetKeyPress(e){
if (map.getZoom() != 4) map.setZoom(4);
map.setCenter(new google.maps.LatLng(39.8282, -98.5795));
document.getElementById("address").value = 'Enter City,State or Zipcode';
document.getElementById("radius").value = '200';
}
</script>
<style>
html, body, #map {
height: 100%;
width: 100%;
margin: 0;
padding: 0;
}
.auto-style1 {
text-align: center;
}
#footer {
position : absolute;
bottom : 0;
height : 40px;
margin-top : 40px;
/* border: 1px solid blue; */
}
</style>
</head>
<body onload='initialize()'>
<div id="map"></div>
<div id="footer" class="auto-style1" style="left: 0px; bottom: 0; width: 100%">
<input type="text" id="address" value="Enter City,State or Zipcode" onclick="if(this.value=='Enter City,State or Zipcode'){this.value=''}" onblur="if(this.value==''){this.value='Enter City,State or Zipcode'}" onkeypress="handleKeyPress(event);" style="width: 183px">
<input type="button" value="Search" onclick="codeAddress();">
<input type="button" value="Reset" onclick="handleResetKeyPress();">
<input type="text" id="radius" value="200" style="width: 42px" onclick="if(this.value=='200'){this.value=''}" onblur="if(this.value==''){this.value='200'}" onkeypress="handleKeyPress(event);"> miles
</div>
</body>
</html>
Here is a working example.
The example uses all_locations - array of example locations.
You can replace that with your locations (e.g. locations you fetch from your DB). You can insert any address to the input bar, e.g. '123 New Street, New York, 56789, NY' and using google.maps.Geocoder the code will geocode that map into LatLng location around which it will draw a radius. Only locations that fall within the radius around the address will show on map. To see the example locations, input "Second Steet, New York" as address.
var map = null;
var radius_circle;
var markers_on_map = [];
var geocoder;
var infowindow;
//all_locations is just a sample, you will probably load those from database
var all_locations = [
{type: "Restaurant", name: "Restaurant 1", lat: 40.723080, lng: -73.984340},
{type: "School", name: "School 1", lat: 40.724705, lng: -73.986611},
{type: "School", name: "School 2", lat: 40.724165, lng: -73.983883},
{type: "Restaurant", name: "Restaurant 2", lat: 40.721819, lng: -73.991358},
{type: "School", name: "School 3", lat: 40.732056, lng: -73.998683}
];
//initialize map on document ready
$(document).ready(function(){
var latlng = new google.maps.LatLng(40.723080, -73.984340); //you can use any location as center on map startup
var myOptions = {
zoom: 1,
center: latlng,
mapTypeControl: true,
mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
navigationControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
geocoder = new google.maps.Geocoder();
google.maps.event.addListener(map, 'click', function(){
if(infowindow){
infowindow.setMap(null);
infowindow = null;
}
});
});
function showCloseLocations() {
var i;
var radius_km = $('#radius_km').val();
var address = $('#address').val();
//remove all radii and markers from map before displaying new ones
if (radius_circle) {
radius_circle.setMap(null);
radius_circle = null;
}
for (i = 0; i < markers_on_map.length; i++) {
if (markers_on_map[i]) {
markers_on_map[i].setMap(null);
markers_on_map[i] = null;
}
}
if (geocoder) {
geocoder.geocode({'address': address}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
var address_lat_lng = results[0].geometry.location;
radius_circle = new google.maps.Circle({
center: address_lat_lng,
radius: radius_km * 1000,
clickable: false,
map: map
});
if (radius_circle) map.fitBounds(radius_circle.getBounds());
for (var j = 0; j < all_locations.length; j++) {
(function (location) {
var marker_lat_lng = new google.maps.LatLng(location.lat, location.lng);
var distance_from_location = google.maps.geometry.spherical.computeDistanceBetween(address_lat_lng, marker_lat_lng); //distance in meters between your location and the marker
if (distance_from_location <= radius_km * 1000) {
var new_marker = new google.maps.Marker({
position: marker_lat_lng,
map: map,
title: location.name
}); google.maps.event.addListener(new_marker, 'click', function () {
if(infowindow){
infowindow.setMap(null);
infowindow = null;
}
infowindow = new google.maps.InfoWindow(
{ content: '<div style="color:red">'+location.name +'</div>' + " is " + distance_from_location + " meters from my location",
size: new google.maps.Size(150,50),
pixelOffset: new google.maps.Size(0, -30)
, position: marker_lat_lng, map: map});
});
markers_on_map.push(new_marker);
}
})(all_locations[j]);
}
} else {
alert("No results found while geocoding!");
}
} else {
alert("Geocode was not successful: " + status);
}
});
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("maps", "3",{other_params:"sensor=false&libraries=geometry"});
</script>
<body style="margin:0px; padding:0px;" >
<input id="address" value="Second Steet, New York" placeholder="Input Address"/>
<select id="radius_km">
<option value=1>1km</option>
<option value=2>2km</option>
<option value=5>5km</option>
<option value=30>30km</option>
</select>
<button onClick="showCloseLocations()">Show Locations In Radius</button>
<div id="map_canvas" style="width:500px; height:300px;">
</body>
</html>
Here is an example of how you could solve this with the geocoding API and some simple geometry.
(Note that I have hardcoded the address and radius for brevity.)
// we assume that you have an array of markers
var markers = [];
//In order to lookup the the position of a zip-code you can use the geocoding API:
// https://developers.google.com/maps/documentation/geocoding/
var geocode_api_base_url = "http://maps.googleapis.com/maps/api/geocode/json?";
var params = {
adress : 05673,
components : "country:us",
sensor : false
}
// This is the result set of markers in area
var in_area = [];
// http://maps.googleapis.com/maps/api/geocode/json?address=05673&components=country:US&sensor=false
$.getJSON( geocode_api_base_url + $.param(params), function(data) {
var location, search_area, in_area = [];
location = data['results'][0]['address_components']['geometry']['location'];
// We create a circle to look within:
search_area = {
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
center : new google.maps.LatLng(location.lat, location.lon),
radius : 500
}
search_area = new google.maps.Circle(search_area);
$.each(markers, function(i,marker) {
if (google.maps.geometry.poly.containsLocation(marker.getPosition(), search_area)) {
in_area.push(marker);
}
});
console.info(in_area);
});
Hi i have an web app where i integrate gmap on it which will look similar to Yelp gmap services. The issues is that when i mouseover the marker the infobox stuck within the box as follow:
the infobox suppose to look like this
Below are my current code for integrate gmap
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="http://google-maps-utility-library-v3.googlecode.com/svn/trunk/infobox/src/infobox_packed.js"></script>
<script type="text/javascript">
var gmap, gpoints = [];
$(document).ready(function() {
initialize();
});
function initialize() {
gmap = new google.maps.Map(document.getElementById('themap'), {
zoom: 8,
streetViewControl: false,
scaleControl: false,
center: new google.maps.LatLng(3.3000000,101.9629796),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
<?php
$content = '<p>Test</p>';
?>
gpoints.push( new point(gmap, '<?php echo $lat; ?>', '<?php echo $long; ?>', '<?php echo $content; ?>') );
}
function point(_map, lat, lng, content) {
this.marker = new google.maps.Marker({
position: new google.maps.LatLng(lat,lng),
map: _map,
zIndex: 11
});
this.content = content;
var gpoint = this;
google.maps.event.addListener(gpoint.marker, 'mouseover', function() {
popup(gpoint);
});
google.maps.event.addListener(_map, 'zoom_changed', function() {
center=gpoint.marker.getPosition();
lat=center.lat();
lng=center.lng();
// alert(lat+"===="+lng);
});
}
function popup(_point) {
_point.popup = new InfoBox({
content: _point.content,
position: _point.marker.getPosition(),
// shadowStyle: 1,
padding: 20,
//backgroundColor: '#ddd',
borderRadius: 10,
arrowSize: 10,
borderWidth: 1,
// borderColor: '#dddddd',
disableAutoPan: true,
arrowPosition: 30,
// backgroundClassName: 'phoney',
arrowStyle: 2
});
_point.popup.open(_point.marker.map, _point.marker);
google.maps.event.addListener(_point.popup, 'domready', function() {
google.maps.event.addDomListener(_point.marker, 'mouseout', function() {
_point.popup.close();
});
});
}
</script>
You may use the option pixelOffset of the infoBox to control the position related to the marker.
The default is 0,0 , which means that the top left corner of the infoBox sticks on the position(of the marker).
To place it top+center, you must explicitly assign to the content of the infobox, and apply a pixelOffset as follows:
pixelOffset:new google.maps.Size(-halfOfWidthOfTheBox,0)
When you don't know the size of the infoBox you may calculate it.
Add this to the domready-callback of _point.popup:
this.setOptions({pixelOffset:new google.maps
.Size(-parseInt(this.div_.offsetWidth/2,10),0)});
what i am trying to achieve is basically mark the location of all the users logged into my chat which is another thing. so i though i'd use geolocation api (http://code.google.com/apis/gears/api_geolocation.html) and store the generated location in a session variable. but its not working. here is the code-`
<?php
$my_lat= $_GET['test']; // get data
$my_long= $_GET['fname'];
$my_name = "vivek";
$lat1=28.635308;
$long1=77.22496;
//$latitude = $_GET['latitude'];
//$longitude = $_GET['longitude'];// get data
echo $my_lat.''.$my_long;
?>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=''
&sensor=true"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var lat = position.coords.latitude;
var longi= position.coords.longitude;
var url = 'bam.php';
//post to the server!
$.get(url, { test: lat,fname: longi },function(data){
alert('data was passed!');
});
}, function() {
//now is when the marking should be done.
handleNoGeolocation(true);
});
}
});
</script>
<script type="text/javascript">
function initialize() {
var myLatlng = new google.maps.LatLng(28.635308,77.22496);
var myOptions = {
zoom: 4,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var thelat = '<?php echo $my_lat;?>';
var thelong = '<?php echo $my_long;?>';
var seslatlng = new google.maps.LatLng(thelat,thelong);
alert(seslatlng);
var marker = new google.maps.Marker({
position: seslatlng,
map: map,
animation: google.maps.Animation.DROP,
title:"Hello world!",
});
}
</script>`
and the problem is. that the variable seslatlng is set to (0,0) always which is not what i want. i am new to PHP and i only have rough idea how server side scripting works. can somebody please fix this?
Instead of using and for assigning values to javascript variables, use:
var thelat = '<?=$my_lat?>';
var thelong = '<?=$my_long?>';
and it will work for you. I have also tried it to assign php variables value to javascript variables.
I don't see anywhere that you are setting seslatlng. If you're wanting this to be a JS variable, add:
var seslatlng = "(<?php echo $my_lat . ',' . $my_lng; ?>)"; // (30.230, 8.030)
when you are using jquery's ajax get function, what you wanna do is call a php function that only returns the locations. this is how is should look:
<?php
if ( $_GET['test'] ) {
$my_lat= $_GET['test']; // get data
$my_long= $_GET['fname'];
$my_name = "vivek";
$lat1=28.635308;
$long1=77.22496;
//$latitude = $_GET['latitude'];
//$longitude = $_GET['longitude'];// get data
echo $my_lat.''.$my_long;
} else {
?>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=''
&sensor=true"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var lat = position.coords.latitude;
var longi= position.coords.longitude;
var url = 'bam.php';
//post to the server!
$.get(url, { test: lat,fname: longi },function(data){
alert('My location is: ' + data);
});
}, function() {
//now is when the marking should be done.
handleNoGeolocation(true);
});
}
});
</script>
<script type="text/javascript">
function initialize() {
var myLatlng = new google.maps.LatLng(28.635308,77.22496);
var myOptions = {
zoom: 4,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var thelat = '<?php echo $my_lat;?>';
var thelong = '<?php echo $my_long;?>';
var seslatlng = new google.maps.LatLng(thelat,thelong);
alert(seslatlng);
var marker = new google.maps.Marker({
position: seslatlng,
map: map,
animation: google.maps.Animation.DROP,
title:"Hello world!"
});
}
</script>
<?php } ?>
The Best way is :
<script type="text/javascript">
var something=<?php echo json_encode($a); ?>;
</script>
Purpose of json_encode is to escpe the quotes and other entities <?php echo $a; ?> can break your code.