I want to know how to make some sort of event in javascript that will be triggered ever time when new data is inserted?
I need this so I can use live tracking in google maps.
For example this is the code that I have found on geolocation page:
function scrollMap(position)
{
// Scrolls the map so that it is centered at (position.coords.latitude,position.coords.longitude).
}
// Request repeated updates.
var watchId = navigator.geolocation.watchPosition(scrollMap);
function buttonClickHandler()
{
// Cancel the updates when the user clicks a button.
//I want to put my code in here so for example when I click button live tracking starts.
navigator.geolocation.clearWatch(watchId);
}
This is my code that I am using to retrieve array of the data:
function initialize() {
var myLatLng = new google.maps.LatLng(0, 180);
var myOptions = {
zoom: 3,
center: myLatLng,
mapTypeId: google.maps.MapTypeId.TERRAIN
};
var map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
var flightPlanCoordinates = [<?php echo implode(',', $coordinates) ?>];
var flightPath = new google.maps.Polyline({
path: flightPlanCoordinates,
strokeColor: "#FF0000",
strokeOpacity: 1.0,
strokeWeight: 2
});
flightPath.setMap(map);
}
How can I make my code to work and get one last result every time it is inserted in the database? And show it on the map in the google code that is provided at the begining of my question.
Database is mysql it has ID,Latitude and Longitude.
EDIT:
This is my PHP code that fetches all data from database and put them in the array for google maps:
$coordinates = array();
$result = dbMySql::Exec('SELECT Latitude,Longitude FROM data');
while ($row = mysqli_fetch_assoc($result))
$coordinates[] = 'new google.maps.LatLng(' . $row['Latitude'] . ', ' . $row['Longitude'] . ')';
The simplest solution is to poll your server. Ask for entries created within the last X minutes and add the new entries.
Related
What I have:
The markers was created by a form submission, the form contains a postcode input. The below javascript will take this postcode and display as markers on google map. (this is a different page)
page1.php (code below)I have a php array, this array contains all infoWindow data and the javascript is to create map, markers and inforwindows.
<?php
..............
$info= array();
foreach($details as $d) {
$info[] = "<div id='infoData'>".$d['name'].$d['quantity']."<button id='details' onclick='window.location.href= \\\"page2.php\\\"'>Detail</button>"."<div>";
}
//.........
?>
The above code is everything on the infoWindow. Click that button in the products array will going to page2.php
<script>
//...................
function init() {
var mapDiv = document.getElementById("map");
var mapOptions = {
center: new google.maps.LatLng(51.528308,-0.3817765),
zoom: 12,
mapTypeId: 'roadmap'
};
var map = new google.maps.Map(mapDiv, mapOptions);
///////////////add markers//////////
var addressArray = ("abc", "def","xxx"), infoArray = (<?php echo $i; ?>);
var geocoder = new google.maps.Geocoder();
for (var i = 0, j=addressArray.length; i < j; i++) {
var info = infoArray[i];
geocoder.geocode({'address': addressArray[i]}, createCallback(info, map));
} //callback function
}
function createCallback(info, map) {
var callback = function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
title: 'Click for more details'
});
//..................
</script>
What I want to achieve:
page2.php I want to show more details of that page1.php button in infowindow I just clicked. How should I do this? Any hint??
I wrote php code on page two, but I just getting all records out,
there's no associations between that marker just clicked and the page2 record. How can I achieve this? page two do not contain any map, just purely text data.
In your code you can pass a unique key or id of that record you want to show on page2.php and get that id using $_GET method and use to show details of that marker.
on page1.php
<?php
..............
$info= array();
foreach($details as $d) {
$info[] = "<div id='infoData'>".$d['name'].$d['quantity']."<button id='details' onclick='window.location.href= \\\"page2.php?marker=".$d['id']."\\\"'>Detail</button>"."<div>";
}
//.........
?>
on page2.php
$infomarker = $_GET['marker'];
Use $infomarker to get the all the details.
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
I'm working in vehicle tracking system, here I have stored GPS data in MySql. What I need do is to show marker in Google Map. Every row data which denotes every second's GPS data. here my problem is I'm not able to show marker in Google map for every second.
Note: I am using timer function in js, Thats why Each and every second a variable is assigned and that variable will match with every second data in db.
This is my code:
<script type="text/javascript">
<?php $vehi = 1; ?>
window.setInterval(function initialize()
{
<?php
$sql= mysql_query("select * from maploca where id='$vehi'");
$sqlnm = mysql_num_rows($sql);
$sqlqry=mysql_fetch_object($sql);
?>
<?php $vehi++;?>
var json = [
{ "lat":<?php echo $sqlqry->latitude; ?>,
"lng":<?php echo $sqlqry->longitude; ?> }]
var latlng = new google.maps.LatLng(<?php echo $sqlqry->latitude;?>,<?php echo $sqlqry->longitude;?>);
var myOptions = {
zoom: 18,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var polylineCoordinates = [
new google.maps.LatLng(<?php echo $sqlqry->latitude;?>,<?php echo $sqlqry->longitude;?>)];
var polyline = new google.maps.Polyline({
path: polylineCoordinates,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 2,
editable: true
});
polyline.setMap(map);
for (var i = 0, length = json.length; i < length; i++) {
var data = json[i],
latLng = new google.maps.LatLng(data.lat, data.lng);
// Creating a marker and putting it on the map
var marker = new google.maps.Marker({
position: latLng,
map: map
});
}
}, 1000);
</script>
You need to use AJAX each time the timer ticks or refresh your page every 1 second. Obviously the later is not a very good idea. The reason is that the PHP on the page does not get executed every time the timer ticks (only on first load).
You will have to write an second file you return the latitude longitude data you require to show the pin.
ie: ( uses jQuery )
LATLONG SERVICE: ( /ajax/getlatlong.php?vid=1 )
<?php ob_start();
header("Content-Type: application/javascript");
/*
IMPORTANT DO SOME FUNCTION HERE TO MAKE SURE THE REQUEST
IS COMING FROM YOUR SITE AND NOT SOMEONE STEALING YOUR
DATA (session var, etc)
*/
$sql= mysql_query("select * from maploca where id='" .
mysql_real_escape_string($_GET['vid']) . "'");
$sqlnm = mysql_num_rows($sql);
$ll = array();
while ( $sqlqry = mysql_fetch_object($sql) ) {
$ll[] = "{".
"\"lat\": " . $sqlqry->latitude . ", " .
"\"lng\": " . $sqlqry->longitude .
"}";
}
echo $_GET['callback'] . "([" . implode(",", $ll) . "]);";
?>
THE MAP PAGE:
<script type="text/javascript">
<?php $vehi = 1; ?>
var myGM = function() {
var me = this;
<?php
$sql= mysql_query("select * from maploca where id='$vehi'");
$sqlnm = mysql_num_rows($sql);
$sqlqry=mysql_fetch_object($sql);
?>
<?php $vehi++;?>
var json = [{
"lat":<?php echo $sqlqry->latitude; ?>,
"lng":<?php echo $sqlqry->longitude; ?>
}];
var latlng = new google.maps.LatLng(json[0].lat,json[0].lng);
var myOptions = {
zoom: 18,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var polylineCoordinates = [latlng];
var polyline = new google.maps.Polyline({
path: polylineCoordinates,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 2,
editable: true
});
polyline.setMap(map);
window.setInterval(function() {
$.getJSON( "/ajax/getlatlong.php?vid=1&callback=?" )
.done( function (data) {
me.updateMap(data);
});
}, 2000);
this.updateMap = function(data) {
$(data).each(function() {
var latLng = new google.maps.LatLng(this.lat, this.lng);
// Creating a marker and putting it on the map
var marker = new google.maps.Marker({
position: latLng,
map: me.map
});
});
}
}
window.onload = function() {
window.trackingMap = new myGM();
}
</script>
Something like that should do the trick
This code will not work. You mix PHP and JS in a way it shouldn't be mixed.
I suggest create 2 separeted parts for displaying (JS) and fetching data (PHP).
window.setInterval should call php page which will return coordinates according to timeparam.
Javascript will iterate it's own variable (not php variable) and call using ajax php webpage adding new markers to map.
ex. Add multiple markers to google maps from json
I am developing a Web Based Application using PHP, MongoDB, Javascript, and Google Maps API V3.
I was able to easily generate and display markers on a google map by converting the MongoDB array using json_encode. Here's an example map with markers and infowindow.
Markers and InfoWindow
However, when I try to implement the Google Maps MarkerClusterer method, the markers disappears. I followed Google Map's "A Simple MarkerClusterer Example" as a guide.
I also tried declaring a global cluster object, passing it an empty array,
var markerCluster = new MarkerClustrer(map, markers);
then using markerCluster.addMarkers(markers, true); as alternate method with no luck.
It seems pretty simple but somehow, it is not displaying the markers. I also tried commenting out the whole infoWindow/OnClick event section so I don't think its related to that. Any help is greatly appreciated.
PHP MongoDB Query:
<?php
// Connect to Mongo and set DB and Collection
try
{
$mongo = new Mongo();
$db = $mongo->selectDB('twitter');
$collection = $db->selectCollection('tweets');
}
catch(MongoConnectionException $e)
{
die("Failed to connect to Twitter Database ". $e->getMessage());
}
// The hotspots array will contain the data that will be returned
$tweets = array();
// Return a cursor of tweets from MongoDB
$cursor = $collection->find();
// Try catch for catching whether there are tweets to display
$count = 0;
try
{
$count = $cursor->count();
}
catch (MongoCursorException $e)
{
die(json_encode(array('error'=>'error message:' .$e->getMessage())));
}
// Loops through the cursor again specifically for querying all geo locations
// Unlike table display of tweets, this cursor is not limited by pages.
foreach($cursor as $id => $value)
{
$mapLocations[] = array
(
'id'=>$value['_id'],
'screen_name'=>$value['screen_name'],
'name'=>$value['name'],
'tweet'=>$value['tweet'],
'hashtags'=>$value['hashtags'],
'lat'=>$value['geo']['lat'],
'long'=>$value['geo']['long'],
'date'=>$value['date'],
'img'=>$value['img'],
'specImg'=>$value['specImg']
);
}
// var_dump($mapLocations);
?>
Javascript Function:
function initialize()
{
// Converts MongoDB information to JSON, ready for Javascript
var tweets = <?php echo json_encode($mapLocations); ?>;
// Sets google maps options
var myOptions =
{
// Centers on Maui...
center: new google.maps.LatLng(20.80362, -156.321716),
zoom: 7,
mapTypeId: google.maps.MapTypeId.TERRAIN
};
// Sets Marker Clusterer Options
var mcOptions =
{
gridSize: 50, maxZoom: 15
};
// Generates Google Map and applies the defined options above.
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
// Infowindow for displaying information for onClick event
// Content must be inside the google.maps.event function
// Otherwise the same content will be entered on all markers
var infoWindow = new google.maps.InfoWindow({});
var markerCluster = null; // Initializes markerCluster
var markers = []; //Array needed to pass to MarkerClusterer
// Loops through each tweet and draws the marker on the map.
for (var i = 0; i < tweets.length; i++)
{
var tweet = tweets[i];
if(tweet.lat != null || tweet.long != null)
{
var myLatLng = new google.maps.LatLng(tweet.lat, tweet.long);
//document.write(" Latitude: " + tweet.lat + " Longitude: " + tweet.long + " <br> ");
var marker = new google.maps.Marker({
position: myLatLng,
//icon: "markers/flag.png",
//map: map,
});
markers.push(marker);
google.maps.event.addListener(marker, 'click', (function(marker, i)
{
return function()
{
// Generates a table for infoWindow
var content = "<table class='popup'>";
// Check if image exits, otherwise show no image icon
if(tweets[i].specImg != null)
{
content += "<tr><th width=75 ><a href=" + tweets[i].specImg + ">";
content += "<img height=75 width=75 src=" + tweets[i].specImg + "></a>";
}
else
{
content += "<tr><th width=75><img height=75 width=75 src=images/noimage.jpg>";
}
// Concatanate screen name and tweet
// Will work on trimming information
content += "</th><td>" + tweets[i].screen_name + " says...<br>";
content += "''" + tweets[i].tweet + "''<br>";
content += "on " + tweets[i].date + "</td>";
content += "</table>";
// Zoom into marker on click
map.setZoom(15);
map.setCenter(marker.getPosition());
// Sets the infoWindow content to the marker
infoWindow.setContent(content);
infoWindow.open(map, marker);
}
})(marker, i));
}
}
var markerCluster = new MarkerClusterer(map, markers);
}
#Robbie:
The JSONned $mapLocations becomes a multidimensional array but I simplified the $mapLocations to only store a 2D lat and long. The javascript source code becomes as follow.
var tweets = [{"lat":20.87179594,"long":-156.47718775},{"lat":20.87195633,"long":-156.47714356},{"lat":20.87138419,"long":-156.47719744},{"lat":21.3320704,"long":-157.8685716},{"lat":null,"long":null},{"lat":21.36509415,"long":-157.92824454},{"lat":21.3320825,"long":-157.8684742},{"lat":null,"long":null},{"lat":21.33673131,"long":-157.86824},{"lat":21.332507,"long":-157.86635342},{"lat":null,"long":null},{"lat":null,"long":null},{"lat":null,"long":null},{"lat":37.36520709,"long":-121.92386941},{"lat":37.2499758,"long":-121.86462506},{"lat":37.36278955,"long":-121.90521146},{"lat":null,"long":null},{"lat":37.36278955,"long":-121.90521146},{"lat":null,"long":null},{"lat":null,"long":null},{"lat":null,"long":null},{"lat":null,"long":null},{"lat":null,"long":null},{"lat":null,"long":null},{"lat":20.88944108,"long":-156.4761887},{"lat":37.36273157,"long":-121.90479984},{"lat":20.85102618,"long":-156.65936351},{"lat":20.88949978,"long":-156.4762491},{"lat":null,"long":null},{"lat":21.3320168,"long":-157.8685715},{"lat":null,"long":null},{"lat":null,"long":null},{"lat":null,"long":null}];
FINALLY FIGURED IT OUT:
As I expected, it was something very simple.
Apparently you need to download the markerclusterer.js file from the Google Maps Utility Library. I thought the clusterer was already built in into the API itself.
I fixed it by downloading the script into server and referencing it like so
<script type="text/javascript" src="markerclusterer.js"></script>
Anyways, thanks everyone for the help!
I think there may be a couple of issues:
The infowindow is required per marker, you are sharing one infowindow for all the markers and repeatedly changing its contents.
Also check that you don't fall into the closure trap. I could retpye it all, but you basically need to create a function out of the closure. There is an explination of how to do this at http://www.robertbolton.com/blog/google-maps-v3-multiple-markers-and-infowindows-in-a-loop
Goog day!
I have a very simple implementation of google maps, which allows my users to draw polylines anywhere on the map canvas.
When starting afresh, the polyline segments are visible on the map and the polyline is stored inside a mySql database using PHP.
// When editing a map with a polyline:
If a user decides to change the polyline, i load the previous polyline from the database and it is visible to the user. When they click on the button to draw a polyline it wil clear the previous polyline from the map and allow them to start afresh, however, once they start clicking away on the map, the new polyline segments is no visible on the map, but is saves correctly to the database.
Here is what i've done so far:
var map;
var polyline = null;
var polylinePath = null;
// HERE I INITIALIZE MY MAP ETC ETC ...
// IN EDIT MODE I ALLOW THE FOLLOWING FUNCTION TO BE CALLED FIRST TO LOAD ANY EXISITNG POLYLINES FOR THE USER
// THIS WORKS FINE, IT SHOWS THE PREVIOUS POLYLINE ON THE MAP.
function loadBasePolylines($mapGuid)
{
var loadUrl = 'classes/Ajax_System.php';
$.getJSON(loadUrl+"?action=loadMapPolylines&mapId="+mapGuid, function(json) {
if(json[0]['hasPolylines'] == 'yes'){
var polylinesArray = [];
var prepath = polylinePath;
if(prepath){
prepath.setMap(null);
}
var points = json[0].Points;
for (i=0; i<points.length; i++) {
polylinesArray.push(new google.maps.LatLng(points[i].lat,points[i].lon));
bounds.extend(new google.maps.LatLng(points[i].lat,points[i].lon));
}
polyline = new google.maps.Polyline({
strokeColor: json[0]['lineColour'],
strokeOpacity: 0.5,
strokeWeight: json[0]['lineThickness'],
clickable: false,
path: polylinesArray
});
polylinePath = polyline.getPath();
polyline.setMap(map);
map.fitBounds(bounds);
}
});
}
// WHEN THE USER PRESS THE "DRAW PATH" BUTTON, THE FOLLOWING FUNCTION IN QUESTION IS CALLED:
function startPolyline()
{
if(polyline != null){
var answer = confirm("This will clear the current polyline from the map. Are you sure you want to continue?");
if(answer){
polyline.setMap(null);
if (tempMarkers) {
for (i in tempMarkers) {
tempMarkers[i].setMap(null);
}
tempMarkers.length = 0;
}
} else {
return;
}
}
var polyOptions = {
strokeColor: polylineColor,
strokeOpacity: polyLineOpacity,
strokeWeight: polyLineWidth,
clickable: false
}
polyline = new google.maps.Polyline(polyOptions);
polyline.setMap(map);
// Add a listener for the click event
google.maps.event.addListener(map, 'click', addPolylinePoint);
}
function addPolylinePoint(event)
{
var path = polyline.getPath();
path.push(event.latLng);
var marker = new google.maps.Marker({
position: event.latLng,
title: '#' + path.getLength(),
icon: '<?php echo URL; ?>public/mapIcons/mm_20_red.png',
map: map
});
tempMarkers.push(marker);
}
What i've tried so far:
Check the color codes are in correct format: YES
Check Lat Lon order and values: YES
Any help will sincerely be appreciated. Thank you in advance.
Wow, I've solved the disappearing polyline issue after reading through my question again. Hopefully this will help someone out there one day:
In my code where i load the polylines from the database:
function loadBasePolylines($mapGuid)
{
.
.
.
polyline = new google.maps.Polyline({
strokeColor: json[0]['lineColour'],
strokeOpacity: 0.5,
strokeWeight: json[0]['lineThickness'],
clickable: false,
path: polylinesArray
});
}
I set the stroke opacity to 0.5 (Equal to 50%) right...
But then, just when i start the polyline tool in ...
function startPolyline()
var polyOptions = {
strokeColor: polylineColor,
strokeOpacity: polyLineOpacity,
strokeWeight: polyLineWidth,
clickable: false
}
... i set the opacity to an unset variable called polyLineOpacity.
Once i added the global variable and applied the loaded value in ...
function loadBasePolylines($mapGuid)
{
.
.
.
strokeOpacity = json[0]['lineOpacity'] * 100;
polyline = new google.maps.Polyline({
strokeColor: json[0]['lineColour'],
strokeOpacity: strokeOpacity,
strokeWeight: json[0]['lineThickness'],
clickable: false,
path: polylinesArray
});
}
... the polylines with the correct opacity displayed correctly again!
I call this developers brain-freeze.
Tkx!
try reinitiating the map variable in the startPolyline function
map = new google.maps.Map(document.getElementById('id of your map')):
I'm connecting a Google Map to a MySQL database to list distributors all over the world, and I seem to be having a few issues.
Sometimes the page itself will not load at all in Firefox (v4 on Mac). It's temperamental on my machine (FF v3.6 Mac) and a Windows machine (FF v4 Win 7), ok in Safari/Opera, doesn't load at all in IE 9 (Win 7). Not sure if it's a network issue or code.
Load time is pretty slow. Might be because the map covers the whole page (will create a square block to place it in).
The URL of the page is here and I used the code from Sean Feeney's page.
The code I have is:
<script src="http://maps.google.com/maps?file=api&v=2&key=<I entered my key here>" type="text/javascript"></script>
<body onUnload="GUnload()">
<div id="map" style="position:absolute;top:0px;bottom:0px;left:0;right:0;"></div>
</body>
<script type="text/javascript">
//<![CDATA[
var map;
var latlngbounds;
if (GBrowserIsCompatible()) {
function createMarker(point, address) {
var marker = new GMarker(point);
var html = address;
GEvent.addListener(marker, 'click', function() {
marker.openInfoWindowHtml(html);
});
return marker;
}
function extendBounding(point) {
latlngbounds.extend(point);
var zoom = map.getBoundsZoomLevel(latlngbounds);
if (zoom < 10) {
zoom = 12;
}
map.setCenter(latlngbounds.getCenter(), zoom);
}
}
map = new GMap2(document.getElementById("map"));
map.addControl(new GLargeMapControl3D());
map.addControl(new GMapTypeControl());
latlngbounds = new GLatLngBounds();
GDownloadUrl("genxml.php", function(data) {
var xml = GXml.parse(data);
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var address = markers[i].getAttribute("address");
var point = new GLatLng(parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var marker = createMarker(point, address);
map.addOverlay(marker);
extendBounding(point);
}
});
}
//]]>
</script>
The code that gets the data is the same as the example.
Any ideas as to why it doesn't always load in the browsers, and why it seems to take a while to load?
Thanks,
Adrian
Ideally you should wrap the code that loads the map inside a document ready or window load event.
I notice that your code is not nested properly inside the GBrowserIsCompatible() block so please fix that.
As far as I remember, Google maps API v2 requires you to call the setCenter() method before doing any operations on the map. So to begin with, set the center to (0, 0) immediately after creating the map.
I notice that you're downloading XML data before you add markers to the map. You must take into account the time taken by the server to serve the XML data. If you've called the setCenter() before downloading the XML, the map will display while the XML downloads asynchronously.
Inside the code that handles the XML data: when you add a marker, do not call setCenter() immediately. Doing so will cause the function to be called 1000 times if you have 1000 markers in your XML. Instead, just call latlngbounds.extend(point). Once you have iterated the loop, calculate the zoom/center and call setCenter(). This way you will end up calling this function only twice.
Edit
I've figured out what the problem is. The genxml.php randomly returns the string Google Geo error 620 occurred which cannot be parsed as XML which raises JavaScript errors and no markers are shown. Better have a look at the code of that file and see why this happens randomly. On other times when that file actually returns valid XML, the markers appear as expected.
It appears Google recently tightened geocoding requests. If you send 10 too fast, it cuts you off with 620 error. The solution they recommend is adding a dynamic timer. Other stackoverflow posts suggested a 0.25 second static timer was good enough, but I've found Google's recommendation of using a while loop that increments the timer value as needed works better. For example:
// Initialize delay in geocode speed
public $delay = 0;
public function lookup(arguments)
{
$geocode_pending = true;
while ($geocode_pending) {
$search = //address string to search;
$response = $this->performRequest($search, 'xml');
$xml = new SimpleXMLElement($response);
$status = (int) $xml->Response->Status->code;
switch ($status) {
case self::G_GEO_SUCCESS:
require_once('placemark.php');
$placemarks = array();
foreach ($xml->Response->Placemark as $placemark)
$placemarks[] = Placemark::FromSimpleXml($placemark);
$geocode_pending = false;
return $placemarks;
case self::G_GEO_TOO_MANY_QUERIES:
$delay += 100000;
case self::G_GEO_UNKNOWN_ADDRESS:
case self::G_GEO_UNAVAILABLE_ADDRESS:
return array();
default:
throw new Exception(sprintf('Google Geo error %d occurred', $status));
}
usleep($delay);
}
}
You can run your map code with window.load after everything is loaded:
jQuery(document).ready(function initAutocomplete() {
var p_lag=$('#longitude').val();
var p_lat=$('#latitude').val();
if(p_lat==''){
var p_lat=20.593684;
}
if(p_lag==''){
var p_lag=78.96288000000004 ;
}
var myLatLng = {lat: p_lat,lng: p_lag};
var map = new google.maps.Map(document.getElementById('dvMap'), {
center: myLatLng,
zoom: 5,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker = new google.maps.Marker({
position: myLatLng,
draggable: true,
map: map,
title: 'Map'
});
// Create the search box and link it to the UI element.
var input = document.getElementById('pac-input');
var searchBox = new google.maps.places.SearchBox(input);
//map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
// Bias the SearchBox results towards current map's viewport.
map.addListener('bounds_changed', function () {
searchBox.setBounds(map.getBounds());
});
//Click event for getting lat lng
google.maps.event.addListener(map, 'click', function (e) {
$('input#latitude').val(e.latLng.lat());
$('input#longitude').val(e.latLng.lng());
});
google.maps.event.addListener(marker, 'dragend', function (e) {
$('input#latitude').val(e.latLng.lat());
$('input#longitude').val(e.latLng.lng());
});
var markers = [];
// [START region_getplaces]
// Listen for the event fired when the user selects a prediction and retrieve
// more details for that place.
searchBox.addListener('places_changed', function () {
var places = searchBox.getPlaces();
if (places.length == 0) {
return;
}
// Clear out the old markers.
/*markers.forEach(function (marker) {
marker.setMap(null);
});*/
markers = [];
// For each place, get the icon, name and location.
var bounds = new google.maps.LatLngBounds();
places.forEach(function (place) {
var 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(25, 25)
};
// Create a marker for each place.
markers.push(new google.maps.Marker({
map: map,
icon: icon,
title: place.name,
position: place.geometry.location
}));
$('#latitude').val(place.geometry.location.lat());
$('#longitude').val(place.geometry.location.lng());
marker.setPosition(place.geometry.location);
if (place.geometry.viewport) {
// Only geocodes have viewport.
bounds.union(place.geometry.viewport);
} else {
bounds.extend(place.geometry.location);
}
map.fitBounds(bounds);
});
});
}
);