I just wondered if anyone knew of a simple script available that will do the following:
Show Google map location of a particular vendor by getting its name from URL. Like we see in various listing websites like Justdial, IndiaMart, Zomato and a lot more. More clearly if my URL is
www.example.com/list.php?city=Delhi
It will show Delhi on google map embed on my list.php web page.
Does anyone know if something like this already exists in PHP?
Thanks in advance.
This will help you.
Html Part.
<div id="map" style="width:100%; height:500px;"></div>
Javascript:
function initMap() {
var latitude = your latitude;
var longitude = Your longitude;
var myLatlng = {lat: parseFloat(latitude), lng: parseFloat(longitude)};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: myLatlng
});
var address = Address;
var infowindow = new google.maps.InfoWindow({
content: address
});
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: 'Click to zoom'
});
marker.addListener('click', function () {
infowindow.open(map, marker);
});
}
And finally you have to include map library.
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=Google key&callback=initMap">
</script>
Related
I have a code of generate map image using Google map api display below :
<img src="https://maps.googleapis.com/maps/api/staticmap?center='<?php echo $madd; ?>'&zoom=7&size=700x300&markers=icon:http://chart.apis.google.com/chart?chst=d_map_pin_icon%26chld=medical%7Clabel:'<?php echo $mlabel; ?>'"/>
Using above code display here google red marker icon but I want to display custom marker icon.
Please help me.
You can try this one i think this one being helpful to you
http://maps.google.com/maps/api/staticmap?center=21.19365498864821,72.8217601776123&size=200x200&zoom=12&maptype=roadmap&markers=icon:%20http://ijiya.com/images/marker-images/image.png|shadow:true|21.19365498864821,72.8217601776123&sensor=false&key=ABQIAAAAjU0EJWnWPMv7oQ-jjS7dYxQGj0PqsCtxKvarsoS-iqLdqZSKfxRdmoPmGl7Y9335WLC365hfg5yrjskd999
You can simply achieve it using java-script
var image = '../images/pin.png';
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: 'YOUR MARKER TITLE',
icon:image
});
where image is your custom marker PNG image,
So your Java-Script code should look like this
var options = {
mapTypeControlOptions: {
mapTypeIds: ['Styled']
},
center: new google.maps.LatLng(30.085100, 31.328230),
zoom: 16,
disableDefaultUI: true,
mapTypeId: 'Styled'
};
var div = document.getElementById('surabaya');
var map = new google.maps.Map(div, options);
var myLatLng = { lat: 30.085100, lng: 31.328230 };
var image = '../structure/static/pin.png';
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: 'PMAS',
icon:image
});
var styledMapType = new google.maps.StyledMapType(styles, { name: 'Styled' });
map.mapTypes.set('Styled', styledMapType);
};
You can simply use this PHP script. It is free and has lots of features. With it, you can manage your maps without even one line coding.
I have a php application that stores Lng-Lat Coordinates to my database.
I would like to show all these places to a google map.
Edit: I have 6000 coordinates, I would like to do this in some way automatically.
Thank you
There are articles for that, which you can find nice and easily on Google
https://developers.google.com/maps/articles/phpsqlajax_v3
If you have several locations, you can use the following code:
var coords = [
[40.980542, 55.111786],
[42.329036, 55.222452],
[44.280249, 54.333]
];
function initialize() {
var myLatlng = new google.maps.LatLng(coords[0][0], coords[0][1]);
var myOptions = {
zoom: 4,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map"), myOptions);
for (var i = 0; i < coords.length; i++) {
var latlng = new google.maps.LatLng(coords[i][0], coords[i][1]);
var marker = new google.maps.Marker({
position: latlng,
map: map,
title: "marker : " + (i + 1)
});
}
}
google.maps.event.addDomListener(window, 'load', initialize);
Check out a working example in JSfiddle.
Also, take a look at Google Places API.
Its a service that returns information about Places using HTTP requests
Here is the Initialise function.....
function initialize() {
Here the variables $Latitude,$Longitude are array values so how can i store them in Javascript Variables so that they can store the above array values....
var lat='<?php echo $Latitude?>';
var lon='<?php echo $Longitude?>';
var latlng = new google.maps.LatLng(lat,lon);
var myOptions = {
zoom: 10,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
Here how can i loop the geocoder to show multiple areas using above array variables...
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
geocoder = new google.maps.Geocoder();
var marker = new google.maps.Marker({
position: latlng,
map: map,
title: "Hello World!"
});
}
Its my sample code to plot multiple areas in google map by using area name or lat,lng.
var map;
var geocoder;
var marker;
var people = new Array();
var latlng;
var infowindow;
$(document).ready(function() {
ViewCustInGoogleMap();
});
function ViewCustInGoogleMap() {
var mapOptions = {
center: new google.maps.LatLng(11.0168445, 76.9558321), // Coimbatore = (11.0168445, 76.9558321)
zoom: 7,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
// Get data from database. It should be like below format or you can alter it.
var data = '[{ "DisplayText": "adcv", "ADDRESS": "Jamiya Nagar Kovaipudur Coimbatore-641042", "LatitudeLongitude": "10.9435131,76.9383790", "MarkerId": "Customer" },{ "DisplayText": "abcd", "ADDRESS": "Coimbatore-641042", "LatitudeLongitude": "11.0168445,76.9558321", "MarkerId": "Customer"}]';
people = JSON.parse(data);
for (var i = 0; i < people.length; i++) {
setMarker(people[i]);
}
}
function setMarker(people) {
geocoder = new google.maps.Geocoder();
infowindow = new google.maps.InfoWindow();
if ((people["LatitudeLongitude"] == null) || (people["LatitudeLongitude"] == 'null') || (people["LatitudeLongitude"] == '')) {
geocoder.geocode({ 'address': people["Address"] }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
latlng = new google.maps.LatLng(results[0].geometry.location.lat(), results[0].geometry.location.lng());
marker = new google.maps.Marker({
position: latlng,
map: map,
draggable: false,
html: people["DisplayText"],
icon: "images/marker/" + people["MarkerId"] + ".png"
});
//marker.setPosition(latlng);
//map.setCenter(latlng);
google.maps.event.addListener(marker, 'click', function(event) {
infowindow.setContent(this.html);
infowindow.setPosition(event.latLng);
infowindow.open(map, this);
});
}
else {
alert(people["DisplayText"] + " -- " + people["Address"] + ". This address couldn't be found");
}
});
}
else {
var latlngStr = people["LatitudeLongitude"].split(",");
var lat = parseFloat(latlngStr[0]);
var lng = parseFloat(latlngStr[1]);
latlng = new google.maps.LatLng(lat, lng);
marker = new google.maps.Marker({
position: latlng,
map: map,
draggable: false, // cant drag it
html: people["DisplayText"] // Content display on marker click
//icon: "images/marker.png" // Give ur own image
});
//marker.setPosition(latlng);
//map.setCenter(latlng);
google.maps.event.addListener(marker, 'click', function(event) {
infowindow.setContent(this.html);
infowindow.setPosition(event.latLng);
infowindow.open(map, this);
});
}
}
<script src="http://code.jquery.com/jquery-1.10.2.min.js" type="text/javascript"></script>
<script src="http://maps.googleapis.com/maps/api/js?key=AIzaSyA7IZt-36CgqSGDFK8pChUdQXFyKIhpMBY&sensor=true" type="text/javascript"></script>
<div id="map-canvas" style="width: 800px; height: 500px;">
</div>
This should work for you assuming lat and lon are javascript arrays with the same length:
var map = null;
function initialize() {
var lat='<?php echo $Latitude?>';
var lon='<?php echo $Longitude?>';
// initialize map center on first point
var latlng = new google.maps.LatLng(lat[0],lon[0]);
var myOptions = {
zoom: 10,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var bounds = new google.maps.LatLngBounds();
for (var i=0, i<lat.length; i++) {
var latlng = new google.maps.LatLng(lat[i],lon[i]);
bounds.extend(latlng);
var marker = new google.maps.Marker({
position: latlng,
map: map,
title: "Hello World!"
});
}
// zoom and center the map to show all the markers
map.fitBounds(bounds);
}
<?php
/* lat/lng data will be added to this array */
try{$work=$_GET["service"];}catch(Exception $e){echo 'Authorization Failed.Map may Misbehave or Buggy.Click here to report this';}
$locations=array();
$uname="root";
$pass="";
$servername="localhost";
$dbname="bcremote";
$db=new mysqli($servername,$uname,$pass,$dbname);
$query = $db->query('SELECT * FROM location');
while( $row = $query->fetch_assoc() ){
$name = $row['uname'];
$longitude = $row['longitude'];
$latitude = $row['latitude'];
/* Each row is added as a new array */
$locations[]=array( 'name'=>$name, 'lat'=>$latitude, 'lng'=>$longitude );
}
//echo $locations[0]['name'].": In stock: ".$locations[0]['lat'].", sold: ".$locations[0]['lng'].".<br>";
//echo $locations[1]['name'].": In stock: ".$locations[1]['lat'].", sold: ".$locations[1]['lng'].".<br>";
?>
<script>
//var myLatLng = {lat: -25.363, lng: 131.044};
function initMap() {
var myLatLng = {lat: -25.363, lng: 131.044};
var map = new google.maps.Map(document.getElementById('map'), {
center: myLatLng,
scrollwheel: false,
zoom: 4
});
<?php for($i=0;$i<sizeof($locations);$i++)
{ ?>
var marker = new google.maps.Marker({
map: map,
position: {lat: <?php echo $locations[$i]['lat']?>,lng: <?php echo $locations[$i]['lng']?>},
title: 'Service'
});
<?php } ?>
}
</script>
This code Snippet uses Dynamic Content without using JSON or XML. This below code is what we see in the Browser View Source tool. Hope this helps you...
<script>
//var myLatLng = {lat: -25.363, lng: 131.044};
function initMap() {
var myLatLng = {lat: -25.363, lng: 131.044};
var map = new google.maps.Map(document.getElementById('map'), {
center: myLatLng,
scrollwheel: false,
zoom: 4
});
var marker = new google.maps.Marker({
map: map,
position: {lat: 192.652.231.25,lng: 192.652.231.25},
title: 'Service'
});
var marker = new google.maps.Marker({
map: map,
position: {lat: 192.652.231.25,lng: 192.652.231.25},
title: 'Service'
});
}
</script>
UPDATE 2017
Google maps now supports the creation of maps with multiple locations which you can embed via iframe! Source: https://www.create.net/support/218-how-to-pin-point-multiple-locations-on-google-maps.html
Go to https://www.google.com/maps
Make sure you're signed in - you can do so by clicking the Login button in the top-right corner.
In the top left corner, next to the search box, click the menu icon to expand the menu
Click "Your Places", "Maps" and then click "Create Map" to edit your map.
A new window will pop up. Give your map a title and description, then click "Save".
You can now pinpoint locations manually by clicking the marker icon and placing it directly onto the map, or search for locations using the search box at the top of the screen.
If you're adding locations manually, you can name the location and save to add it to the map. If you're searching and adding specific locations, a green marker will appear on the map and you can click the 'Add to map' link.
Repeat steps 6 and 7 for each location you wish to plot.
Once you have done that save your map again and refresh the page. Then, to get the code to embed your map on to your Create website, please follow these steps:
Make sure you map is public. You can do this by clicking 'Share' beneath the map name.
Under 'Who has access' click 'Change' and make turn it 'On - Public on the web' and save.
Next, click the menu icon and click on the link 'Embed on my site'
The code will then pop up in a new window.
To use this, you will need to paste the code into an HTML fragment on your Create account, and then place the HTML fragment on your chosen page.
Example:
<iframe src="https://www.google.com/maps/d/embed?mid=1tX88xmVMIFW9DQneDff_ZMJtekc" width="100%" height="480"></iframe>
Hey again fine peoples!
I'll start at the top, with my XML file! I have a XML layed out like this:
<?xml version="1.0" encoding="UTF-8"?>
<markers>
<watersource>
<marker name="Large private dam - Plenty of water. Access from whatever Rd." lat="-35.844630" lng="146.313416" type="1"/>
</watersource>
<watersource>
<marker name="Small water tank with fire fighting fittings - Plenty of water. Access from whatever Rd." lat="-35.844630" lng="146.313416" type="1"/>
</watersource>
</markers>
Then I have php file like this to read the XML and display the markers on google maps (irrelevant stuff stripped out):
<?php
{
?>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="util.js"></script>
<script type="text/javascript">
var infowindow;
var map;
function initialize() {
var myLatlng = new google.maps.LatLng(-37.855677, 145.316076);
var myOptions = {
zoom: 13,
center: myLatlng,
disableDefaultUI: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
downloadUrl("watersourcedata.xml", function(data) {
var markers = data.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var latlng = new google.maps.LatLng(parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var marker = createMarker(markers[i].getAttribute("name"), latlng);
}
});
}
var image = 'images/watersource.png';
function createMarker(name, latlng) {
var marker = new google.maps.Marker({position: latlng, map: map, icon: image});
google.maps.event.addListener(marker, "click", function() {
if (infowindow) infowindow.close();
infowindow = new google.maps.InfoWindow({content: name});
infowindow.open(map, marker);
});
return marker;
}
</script>
</head>
<body onload="initialize()">
<FONT SIZE="2">NOTE: Water Source Map Is Under Construction.<BR>
This map once completed will allow brigades to make and maintain a map of major water sources like dams, wells, tanks ect. in their local areas.<BR>
<BR>
Watersource Legend:<BR>
A creek, dam, river, pond ect.(drafting needed) = <img src='images/watersource.png'> <BR>
A water tank, pump ect (drafting NOT needed) = <img src='images/waterwellpump.png'>
<BR>
</FONT>
<div id="map_canvas" style="width:950px; height:450px;"></div>
<?
}
?>
Now, that works all fine however in the XML i have a type. Type 1 (watersource.png) and Type 2 (waterwellpump.png). What I need to do is if it's type 1 in the XML display map marker image 1.. Type 2, marker image 2.. I'm kinda new to this XML caper and am a little lost!! If anyone could point me in the right direction I would be most grateful!
Thanks!
When you are sending the information to create marker, send the image type like this
createMarker(markers[i].getAttribute("name"), latlng, markers[i].getAttribute("type"));
In your createMarker function change it to decide which image to select.
function createMarker(name, latlng, type) {
if(type == 1)
image = 'images/watersource.png';
else
image = 'images/waterwellpump.png';
var marker = new google.maps.Marker({position: latlng, map: map, icon: image});
google.maps.event.addListener(marker, "click", function() {
if (infowindow) infowindow.close();
infowindow = new google.maps.InfoWindow({content: name});
infowindow.open(map, marker);
});
return marker;
}
I have this simple hello world version of a google map api javascript v3 and it works for a static geocode. My data is normal addresses (i.e. "30 rockefeller center, New York, NY").
This data is being called from with php from a mysql database. I can get the address on the page with something like this...For the purpose of this post, say this would have all info: address, city, state, zip code
<?php echo $row_query_details['address'];?>
So, I need to geocode this info for the map. I'm very comfortable with mysql and php, but not as much with javascript. I have been trial/error and researching this for a couple of days.
I have looked everywhere for a working sample or example and feel like this relatively simple problem must have been asked and answered many times over, but I cannot figure it out!
Thanks in advance.
Here is the code I'm working with:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map_canvas { height: 100% }
</style>
<script type="text/javascript"
src="http://maps.googleapis.com/maps/api/js?sensor=false">
</script>
<script type="text/javascript">
function initialize() {
var latlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
var marker = new google.maps.Marker({
position: latlng,
title:"Hello World!"
});
// To add the marker to the map, call setMap();
marker.setMap(map);
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="width:500px; height:500px"></div>
</body>
</html>
Hello and happy anniversary (regarding your question and tutorial).
I am a web-developer and must thank you. I used this tutorial as I currently do not have a way to geocode via submit (lat/long needs to be pulled from address stored in db) as I am consulting an existing site and have minimal access to backend code.
To answer your question regarding marker interactivity, this takes a few easy steps:
1) Provide some content. This is done before declaring the geocoder (var geocoder;):
var contentString =
'line 1'+
'line 2';
2) Underneath the marker declaration ( var marker = new google.maps.Marker({ ), you will need to declare infowindow and add the event listener:
var infowindow = new google.maps.InfoWindow({
content: contentString
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
Edit:
I have successfully pulled array information from a MySQL database by expanding on your method. My method is here:
1) Basic php below:
include (dbinfo.php)
$result = mysql_query( 'SELECT * FROM table')
$count = 0
2) Setting up google maps API:
<script type="text/javascript"
src="http://maps.googleapis.com/maps/api/js?key=yourkey&sensor=false">
</script>
3) Geocoding setup below:
<script type="text/javascript">
var geocoder;
var map;
function initialize() {
var latlng = new google.maps.LatLng(yourlat, yourlong); //This is to center the map
var myOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
<?php //Starts while loop so all addresses for the given information will be populated.
while($row = mysql_fetch_array($result)) //instantiates array
{ ?>
geocoder = new google.maps.Geocoder();
var address = '<?php echo $row['address'].', '.$row['city'].', '.$row['state'].', '.$row['zip'].', '.$row['country']; ?>';
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
//marker generation is done though adding the primary ID to the "marker" variable, so if address "1" has the primary ID of "1", your marker would read "marker1"
var marker<?php print $row['primaryID']; ?> = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
title: "This can be a php variable or whatever you like. It is displayed on hover."
});
//var contentString manages what is seen inside of the popup
var contentString =
'line 1'+
'line 2';
var infowindow = new google.maps.InfoWindow({
content: contentString
});
google.maps.event.addListener(marker<?php print $row['primaryID']; ?>, 'click', function() {
infowindow.open(map,marker<?php print $row['primaryID']; ?>);
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
<?php
$count++;
} //ends while
?>
}
/*end javascript*/
</script>
Thank you very much again for posting this. It was very useful.
You can use your PHP variable into JavaScript by passing php variables in function initialize().
your body tag will look like below;
For Ex:
<body onload="initialize('<?php echo $row_query_details['address'];?>')">
Then you will use this particular variable in your javascript code, your javascript function will look like below:
<script type="text/javascript">
function initialize(address) {
var G_address = address;
var latlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
var marker = new google.maps.Marker({
position: latlng,
title:"Hello World!"
});
// To add the marker to the map, call setMap();
marker.setMap(map);
}
</script>
Now you can use this G_address JavaScript variable dynamically in your G-MAP code..
This will be helpful to you..
So, I'm going to answer my own question here. The first answer provided I was not able to utlize. I'm not sure if the answer was incomplete or I just didnt' follow it. Regardless, here's what the code looks like:
First I had my address components pulling from the mysql db and I assigned them variables, like this:
$county = $row_qry['county'];
$address = $row_qry['address'];
$city = $row_qry['city'];
$state = $row_qry['state'];
Then, my google v3 stuff looks like this:
<script type="text/javascript" src="//maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(34.052234,-118.243685);
var address = '<?php echo $address.', '.$city.', '.$state; ?>';
var myOptions = {
zoom: 14,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
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,
position: results[0].geometry.location
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
</script>
And that sort of answers my question. There are a couple of issues I still need to resolve, such as (a) how to make the marker be clickable and interactive, and (b) the map flashes a the geocode first defined (34.05,-118.24) before showing the correct address.
Both of these issues I need to still resolve, but at least the geocoding is working successfully. Hope this helps someone else.
Thanks!