تنظيم صفحاتك في مجموعات
يمكنك حفظ المحتوى وتصنيفه حسب إعداداتك المفضّلة.
مانو ماركس، فريق Google Geo
تاريخ الإنشاء: ديسمبر 2007
تاريخ التعديل: ديسمبر 2013
الهدف
هذا البرنامج التعليمي مخصّص للمطوّرين الذين لديهم خبرة في لغات البرمجة النصية ويريدون معرفة كيفية استخدام Google Geocoding API لترميز العناوين جغرافيًا ودمجها في ملف KML. على الرغم من أنّ عيّنات الرموز البرمجية معروضة بلغة Python، يمكن تكييفها بسهولة مع معظم لغات البرمجة الأخرى.
الترميز الجغرافي هو عملية تحويل عنوان إلى مجموعة من إحداثيات خطوط الطول والعرض، ما يتيح إمكانية تحديد العناوين على الخريطة. قد تحتاج إلى تحويل العناوين إلى رموز جغرافية
وإدراجها مباشرةً في ملف KML. ويحدث ذلك عادةً، على سبيل المثال، عند إدخال البيانات في نموذج وإنشاء ملفات KML استجابةً للطلبات. يمكن تخزين ملفات KML هذه في قاعدة بيانات أو في نظام ملفات أو إرجاعها إلى NetworkLink يرتبط بملفك.
يُرجى العِلم أنّه عند استخدام هذه الطريقة، عليك الالتزام ببنود الخدمة الخاصة بواجهة Geocoding API، إذ توجد بعض القيود على المدة التي يمكن فيها تخزين النتائج، بالإضافة إلى عدد العناصر التي يمكنك ترميزها جغرافيًا كل يوم.
يوضّح لك هذا البرنامج التعليمي كيفية استخدام Python لتحويل السلسلة "1600 Amphitheatre Pkwy, Mountain View, CA 94043" إلى ما يلي:
KML هي لغة ترميز XML، لذا يمكننا استخدام دوال xml.dom.minidom المضمّنة في Python لإنشاء مستند KML. minidom في Python هو تنفيذ DOM، ويكون DOM متاحًا في معظم لغات البرمجة، لذا يجب أن تكون عملية النقل إلى لغة برمجة أخرى سهلة. إليك الخطوات التي يمكنك اتّباعها:
أنشئ المستند باستخدام xml.dom.minidom.Document() في Python.
أنشئ عنصر <kml> الجذر باستخدام
createElementNS.
أضِفها إلى المستند باستخدام appendChild.
أنشئ عنصر Document باستخدام createElement.
أضِفها إلى عنصر <kml> باستخدام appendChild.
لكل عنوان، أنشئ عنصر <Placemark> باستخدام createElement، وأضِفه إلى عنصر Document. بعد ذلك، أنشئ عنصر <description>
وحدِّد له قيمة العنوان، ثم ألحِقه بالعنصر <Placemark>.
أنشئ عنصر <Point>، وأضِف عنصرًا ثانويًا <coordinates>، ثم أضِفه إلى العنصر <Placemark>.
أرسِل العنوان إلى أداة الترميز الجغرافي في Maps API، والتي سترسل استجابة بتنسيق JSON أو XML.
استخدِم urllib.urlopen() لاسترداد الملف وقراءته في سلسلة.
حلّل الرد واستخرِج عناصر خط الطول وخط العرض.
أنشئ عقدة نصية في العنصر <coordinates>
وعيِّن سلسلة خطوط الطول والعرض كقيمة لها.
اكتب مستند KML في ملف نصي.
نموذج لرمز Python البرمجي
يُرجى العِلم أنّ نموذج الرمز البرمجي أدناه يستخدم متغيّرًا وهميًا باسم mapsKey، وعليك استبدال هذا المفتاح
بالمفتاح الخاص بك.
في ما يلي نموذج رمز لترميز الموقع الجغرافي باستخدام الإصدار 2.7 من Python وإخراج JSON:
importurllibimportxml.dom.minidomimportjsondefgeocode(address,sensor=False):# This function queries the Google Maps API geocoder with an# address. It gets back a csv file, which it then parses and# returns a string with the longitude and latitude of the address.# This isn't an actual maps key, you'll have to get one yourself.# Sign up for one here: https://code.google.com/apis/console/mapsKey='abcdefgh'mapsUrl='https://maps.googleapis.com/maps/api/geocode/json?address='# This joins the parts of the URL together into one string.url=''.join([mapsUrl,urllib.quote(address),'&sensor=',str(sensor).lower()])#'&key=',mapsKey])jsonOutput=str(urllib.urlopen(url).read())# get the response # fix the output so that the json.loads function will handle it correctlyjsonOutput=jsonOutput.replace("\\n","")result=json.loads(jsonOutput)# converts jsonOutput into a dictionary # check status is ok i.e. we have results (don't want to get exceptions)ifresult['status']!="OK":return""coordinates=result['results'][0]['geometry']['location']# extract the geometry returnstr(coordinates['lat'])+','+str(coordinates['lng'])defcreateKML(address,fileName):# This function creates an XML document and adds the necessary# KML elements.kmlDoc=xml.dom.minidom.Document()kmlElement=kmlDoc.createElementNS('http://earth.google.com/kml/2.2','kml')kmlElement=kmlDoc.appendChild(kmlElement)documentElement=kmlDoc.createElement('Document')documentElement=kmlElement.appendChild(documentElement)placemarkElement=kmlDoc.createElement('Placemark')descriptionElement=kmlDoc.createElement('description')descriptionText=kmlDoc.createTextNode(address)descriptionElement.appendChild(descriptionText)placemarkElement.appendChild(descriptionElement)pointElement=kmlDoc.createElement('Point')placemarkElement.appendChild(pointElement)coorElement=kmlDoc.createElement('coordinates')# This geocodes the address and adds it to a element.coordinates=geocode(address)coorElement.appendChild(kmlDoc.createTextNode(coordinates))pointElement.appendChild(coorElement)documentElement.appendChild(placemarkElement)# This writes the KML Document to a file.kmlFile=open(fileName,'w')kmlFile.write(kmlDoc.toprettyxml(' '))kmlFile.close()if__name__=='__main__':createKML('1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA','google.kml')
أمور أخرى يجب أخذها في الاعتبار
تحديد توقيت طلبات الترميز الجغرافي
ستخضع طلبات الترميز الجغرافي للحدود القصوى اليومية لمعدّل طلبات البحث في أداة الترميز الجغرافي. يُرجى الرجوع إلى مستندات Google Geocoding API للحصول على مزيد من المعلومات حول هذه الحدود. لضمان عدم إرسال طلبات بحث بسرعة كبيرة إلى أداة الترميز الجغرافي، يمكنك تحديد فترة تأخير بين كل طلب ترميز جغرافي. يمكنك زيادة هذا التأخير في كل مرة تتلقّى فيها حالة OVER_QUERY_LIMIT، واستخدام حلقة while للتأكّد من ترميز عنوان جغرافيًا بنجاح قبل الانتقال إلى العنوان التالي.
تغيير البلد الأساسي
تمت برمجة أداة الترميز الجغرافي لتحيز نتائجها استنادًا إلى النطاق المصدر.
على سبيل المثال، سيؤدي إدخال "سيراكيوز" في مربّع البحث على maps.google.com إلى ترميز الموقع الجغرافي لمدينة "سيراكيوز، نيويورك"، بينما سيؤدي إدخال طلب البحث نفسه على maps.google.it (نطاق إيطاليا) إلى العثور على مدينة "سيراكوزا" في صقلية. يمكنك الحصول على النتائج نفسها من خلال إرسال طلب البحث هذا عبر الترميز الجغرافي HTTP إلى maps.google.it بدلاً من maps.google.com، ويمكنك إجراء ذلك من خلال تعديل المتغير mapsUrl في نموذج الرمز أعلاه.
يُرجى الرجوع إلى مستندات Geocoding API للحصول على مزيد من المعلومات حول تحديد المنطقة.
ملاحظة: لا يمكنك إرسال طلب إلى خادم maps.google.* غير متوفّر، لذا تأكَّد من توفّر نطاق البلد قبل إعادة توجيه طلبات الترميز الجغرافي إليه. للاطّلاع على البلدان التي تتوفّر فيها رموز الترميز الجغرافي، يُرجى الاطّلاع على هذه المشاركة.
الخاتمة
باستخدام الرمز البرمجي أعلاه، يمكنك الآن تحويل عنوان إلى إحداثيات جغرافية باستخدام Python، وإنشاء ملف KML
<Placemark> منه، وحفظه على القرص. إذا تبيّن لك أنّك بحاجة إلى ترميز جغرافي لعدد أكبر من العناوين يوميًا مما تسمح به الحدود، أو أنّ خدمة الترميز الجغرافي من Google لا تغطي المناطق التي تهمّك، ننصحك باستخدام خدمات ويب إضافية للترميز الجغرافي.
تاريخ التعديل الأخير: 2025-07-27 (حسب التوقيت العالمي المتفَّق عليه)
[[["يسهُل فهم المحتوى.","easyToUnderstand","thumb-up"],["ساعَدني المحتوى في حلّ مشكلتي.","solvedMyProblem","thumb-up"],["غير ذلك","otherUp","thumb-up"]],[["لا يحتوي على المعلومات التي أحتاج إليها.","missingTheInformationINeed","thumb-down"],["الخطوات معقدة للغاية / كثيرة جدًا.","tooComplicatedTooManySteps","thumb-down"],["المحتوى قديم.","outOfDate","thumb-down"],["ثمة مشكلة في الترجمة.","translationIssue","thumb-down"],["مشكلة في العيّنات / التعليمات البرمجية","samplesCodeIssue","thumb-down"],["غير ذلك","otherDown","thumb-down"]],["تاريخ التعديل الأخير: 2025-07-27 (حسب التوقيت العالمي المتفَّق عليه)"],[[["\u003cp\u003eThis tutorial demonstrates how to geocode addresses using the Google Geocoding API and Python, converting them into latitude/longitude coordinates for KML file integration.\u003c/p\u003e\n"],["\u003cp\u003eThe process involves creating a KML document, sending addresses to the Geocoding API, parsing the response for coordinates, and embedding them within KML Placemark elements.\u003c/p\u003e\n"],["\u003cp\u003ePython's xml.dom.minidom library is used for KML document creation, and urllib.urlopen is used for retrieving the geocoding results in JSON format.\u003c/p\u003e\n"],["\u003cp\u003eConsiderations include respecting the Geocoding API's usage limits by implementing delays between requests and adjusting the base country for region-specific results.\u003c/p\u003e\n"],["\u003cp\u003eThe resulting KML file can be used to display geocoded addresses as points on a map, enabling visualization and integration with other geographic data.\u003c/p\u003e\n"]]],[],null,["# Geocoding Addresses for Use in KML\n\n*Mano Marks, Google Geo Team\nAuthored: December 2007\nUpdated: December 2013*\n\nObjective\n---------\n\nThis tutorial is intended for developers who are familiar with\nscripting languages and want to learn how to use the [Google\nGeocoding API](/maps/documentation/geocoding) to geocode addresses and incorporate them into a KML file. While the code samples\nare presented in Python, they can be adapted fairly easily to most other programming languages.\n\n\n*Geocoding* is the process of converting an address into a set of latitude/longitude\ncoordinates, making it possible to indicate addresses on a map. You may want to geocode addresses\nand put them directly into a KML file. This is common, for example, when data is being entered into\na form and you are generating KML files in response to requests. These KML files could be\nstored in a database, in a file system or returned to a NetworkLink that connects to your file.\nNote that when using this technique, you must observe the [Terms of Service](/maps/terms)\nfor the Geocoding API as there are some limitations on the time the results can be stored for, as\nwell as the number of elements that you can geocode each day.\n\nThis tutorial shows you how to use Python to take the string\n\"`1600 Amphitheatre Pkwy, Mountain View, CA 94043`\" and turn it into this: \n\n```text\n\u003c?xml version='1.0' encoding='UTF-8'?\u003e \n\u003ckml xmlns='http://earth.google.com/kml/2.2'\u003e\n \u003cDocument\u003e\n \u003cPlacemark\u003e\n \u003cdescription\u003e1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA\u003c/description\u003e\n \u003cPoint\u003e\n \u003ccoordinates\u003e-122.081783,37.423111,0\u003c/coordinates\u003e\n \u003c/Point\u003e\n \u003c/Placemark\u003e\n \u003c/Document\u003e\n\u003c/kml\u003e\n```\n\nCreate a KML Document\n---------------------\n\nKML is an XML markup language, so we can use Python's built in\n[xml.dom.minidom](http://docs.python.org/lib/module-xml.dom.minidom.html)\nfunctions to create a KML document. Python's minidom is a [DOM](http://www.w3.org/DOM/)\nimplementation, and DOM is supported in most programming languages, so this process should be easy\nto port into another programming language. Here are the steps:\n\n1. Create the document using Python's `xml.dom.minidom.Document()`.\n2. Create the root `\u003ckml\u003e` element using `createElementNS.`\n3. Append it to the document using `appendChild`.\n4. Create a Document element using `createElement`.\n5. Append it to the `\u003ckml\u003e` element using `appendChild`.\n6. For each address, create a `\u003cPlacemark\u003e` element using `createElement`, and append it to the `Document` element. Then, create a `\u003cdescription\u003e` element, assign it the value of the address, and append it to the `\u003cPlacemark\u003e` element.\n7. Create a `\u003cPoint\u003e` element, add a child `\u003ccoordinates\u003e` element, and append it to the `\u003cPlacemark\u003e` element.\n8. Send the address to the Maps API Geocoder, which sends a response in either JSON or XML. Use `urllib.urlopen()` to retrieve the file and read it into a string.\n9. Parse the response and extract the longitude and latitude elements.\n10. Create a text node in the `\u003ccoordinates\u003e` element and assign the longitude/latitude string as its value.\n11. Write the KML document to a text file.\n\nSample Python Code\n------------------\n\n\nNote that the sample code below uses a dummy mapsKey variable---you'll need to replace this key with your\n[own key](https://code.google.com/apis/console/?noredirect).\n\nSample code for geocoding with Python 2.7 and JSON output is shown below: \n\n```python\nimport urllib\nimport xml.dom.minidom\nimport json \n\ndef geocode(address, sensor=False):\n # This function queries the Google Maps API geocoder with an\n # address. It gets back a csv file, which it then parses and\n # returns a string with the longitude and latitude of the address.\n\n # This isn't an actual maps key, you'll have to get one yourself.\n # Sign up for one here: https://code.google.com/apis/console/\n mapsKey = 'abcdefgh'\n mapsUrl = 'https://maps.googleapis.com/maps/api/geocode/json?address='\n \n # This joins the parts of the URL together into one string.\n url = ''.join([mapsUrl,urllib.quote(address),'&sensor=',str(sensor).lower()])\n#'&key=',mapsKey])\n jsonOutput = str(urllib.urlopen(url).read ()) # get the response \n # fix the output so that the json.loads function will handle it correctly\n jsonOutput=jsonOutput.replace (\"\\\\n\", \"\")\n result = json.loads(jsonOutput) # converts jsonOutput into a dictionary \n # check status is ok i.e. we have results (don't want to get exceptions)\n if result['status'] != \"OK\": \n return \"\"\n coordinates=result['results'][0]['geometry']['location'] # extract the geometry \n return str(coordinates['lat'])+','+str(coordinates['lng'])\n\ndef createKML(address, fileName):\n # This function creates an XML document and adds the necessary\n # KML elements.\n\n kmlDoc = xml.dom.minidom.Document()\n \n kmlElement = kmlDoc.createElementNS('http://earth.google.com/kml/2.2','kml')\n\n kmlElement = kmlDoc.appendChild(kmlElement)\n\n documentElement = kmlDoc.createElement('Document')\n documentElement = kmlElement.appendChild(documentElement)\n\n placemarkElement = kmlDoc.createElement('Placemark')\n \n descriptionElement = kmlDoc.createElement('description')\n descriptionText = kmlDoc.createTextNode(address)\n descriptionElement.appendChild(descriptionText)\n placemarkElement.appendChild(descriptionElement)\n pointElement = kmlDoc.createElement('Point')\n placemarkElement.appendChild(pointElement)\n coorElement = kmlDoc.createElement('coordinates')\n\n # This geocodes the address and adds it to a element.\n coordinates = geocode(address)\n coorElement.appendChild(kmlDoc.createTextNode(coordinates))\n pointElement.appendChild(coorElement)\n\n documentElement.appendChild(placemarkElement)\n\n # This writes the KML Document to a file.\n kmlFile = open(fileName, 'w')\n kmlFile.write(kmlDoc.toprettyxml(' ')) \n kmlFile.close()\n\nif __name__ == '__main__':\n createKML('1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA', 'google.kml')\n```\n\nOther Things to Consider\n------------------------\n\n### Timing the Geocode Requests\n\n\nGeocoding requests will be subject to the geocoder's maximum query rate daily limits. Please refer\nto the [Google Geocoding API](/maps/documentation/geocoding) documentation for more\ninformation about these limits. To ensure you don't send queries too rapidly to the geocoder, you\ncan specify a delay between each geocode request. You can increase this delay each time you receive\nan `OVER_QUERY_LIMIT` status, and use a `while` loop to ensure you've\nsuccessfully geocoded an address before iterating to the next one.\n\n### Changing the Base Country\n\n\nThe geocoder is programmed to bias its results depending on the originating domain.\nFor example, entering \"syracuse\" in the search box on maps.google.com will geocode the city of\n\"Syracuse, NY\", while entering the same query on *maps.google.it* (Italy's domain) will\nfind the city of \"Siracusa\" in Sicily. You would get the same results by sending that query\nthrough HTTP geocoding to *maps.google.it* instead of *maps.google.com* ,\nwhich you can do by modifying the `mapsUrl` variable in the sample code above.\nRefer to the Geocoding API documentation for more information on\n[Region Biasing](/maps/documentation/geocoding#RegionCodes).\n\n**Note:** You cannot send a request to a nonexistent\nmaps.google.\\* server, so ensure that a country domain exists before redirecting your geocoding\nqueries to it. For geocode support by country, check out\n[this\npost](http://googlemapsapi.blogspot.com/2007/11/is-google-maps-in-your-neck-of-woods.html).\n\nConclusion\n----------\n\nUsing the code above, you can now geocode an address using Python, create a KML\n`\u003cPlacemark\u003e` out of it, and save it to disk. If you find that you need to\ngeocode more addresses per day than the limits allow, or that the Google geocoder doesn't cover the\nregions you're interested in, then consider using additional geocoding web services.\n\nNow that you know how to geocode your addresses, check out the articles on\n[Using KML in Google Mashup Editor](/kml/articles/kmlgme) and\n[Using PHP and MySQL to create KML](/kml/articles/phpmysqlkml).\nIf you have any problems with or questions about this tutorial, please post in the [Stack Overflow](/maps/support)\nforum."]]